c# Excel的基本操作

ExcelHelper代码:

1 class ExcelHelper
2 {
3 publicstaticvoid SaveData()
4 {
5 string filePath = Environment.CurrentDirectory +"\\Data";
6 if (!Directory.Exists(filePath))
7 {
8 Directory.CreateDirectory(filePath);
9 }
10 string fileName =string.Format("{0}\\{1}.xls", filePath, DateTime.Now.ToShortDateString());
11
12 Excel.Application excelApp =new Excel.ApplicationClass();
13 //新建工作簿
14 if(!File.Exists(fileName))
15 {
16 Excel.Workbook workBookNew = excelApp.Workbooks.Add(true);
17 //新建工作表
18 Excel.Worksheet worksheetNew = workBookNew.ActiveSheet as Excel.Worksheet;
19 workBookNew.SaveAs(fileName, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Excel.XlSaveAsAccessMode.xlNoChange, Missing.Value, Missing.Value, true, false, Missing.Value);
20 }
21 Excel.Workbook workBook = excelApp.Workbooks.Open(fileName, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, false, Missing.Value, Missing.Value, true, false, Missing.Value, false, false, false);
22
23 //新建工作表
24 Excel.Worksheet worksheet = workBook.ActiveSheet as Excel.Worksheet;
25
26 Excel.Range r = worksheet.get_Range(
27 worksheet.Cells[1, 1], worksheet.Cells[3, 3]); //选取单元格
28 r.MergeCells =true;
29
30 r.Value2 ="我爱中华"; //设置单元格内文本
31 r.Font.Name ="黑体"; //设置字体
32 r.Font.Size =20; //字体大小
33 r.Font.Bold =true; //加粗显示
34 r.HorizontalAlignment = Excel.XlHAlign.xlHAlignCenter; //水平居中
35 r.VerticalAlignment = Excel.XlVAlign.xlVAlignCenter; //垂直居中
36
37 worksheet.Cells[4, 1] ="《歌唱祖国》";
38 worksheet.Cells[5, 2] ="《为中华崛起而读书》";
39 excelApp.DisplayAlerts =false;
40 excelApp.AlertBeforeOverwriting =false;
41 workBook.Save();
42 excelApp.Quit();
43 System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp);
44 excelApp =null;
45 System.GC.Collect();
46 }
47 }
48

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zgjjdx.html