C# WinForm创建Excel文件的实例

时间:2022-04-15 05:27:40

实例如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
private bool creatExcel(string xlsfile)
    {
      try
      {
        object missing = System.Reflection.Missing.Value;
        Excel.ApplicationClass myExcel = new Excel.ApplicationClass();
 
        Excel._Workbook xBk;        //工作薄
        Excel._Worksheet xSt;   //工作Sheet 
 
        xBk = myExcel.Workbooks.Add(true);
 
        for (int i = 0; i < 1; i++)
        {
          xSt = (Excel._Worksheet)xBk.ActiveSheet;
          xSt.Name = "Sheet" + i;
          myExcel.Sheets.Add(missing, missing, 1, Excel.XlSheetType.xlWorksheet);
        }
        //myExcel.Visible = true;
        if (xlsfile.ToLower().EndsWith(".xlsx"))
        {
          xBk.SaveAs(xlsfile, 56, missing,
          missing, missing, missing, Excel.XlSaveAsAccessMode.xlShared,
          missing, missing, missing, missing, missing);
        }
        else
        {
          xBk.SaveAs(xlsfile, missing, missing,
          missing, missing, missing, Excel.XlSaveAsAccessMode.xlShared,
          missing, missing, missing, missing, missing);
        }
        myExcel.Quit();
        return true;
      }
      catch (Exception ex)
      {
        MessageBox.Show("Excel创建失败!原因:" + ex.Message);
        return false;
      }
    }

以上这篇C# WinForm创建Excel文件的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。