c#Excelの基本操作

13266 ワード

本文の主な内容:c#はExcelのOpen、Save、セルのマージ、セルの割り当てを実現する.
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

プログラムコード:
1 class Program
2 {
3 staticvoid Main(string[] args)
4 {
5 Console.Title ="Excel Operation Example";
6 ExcelHelper.SaveData();
7 Environment.Exit(0);
8 }
9 }

結果:
私は中華が好きです
 
 
 
『祖国を歌う』
 
 
 
『中華の台頭のために読書する』