欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

C#WinForm创建Excel文件的示例代码分享

程序员文章站 2022-04-01 20:35:11
...
下面小编就为大家带来一篇C# WinForm创建Excel文件的实例。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧

实例如下:

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文件的示例代码分享的详细内容,更多请关注其它相关文章!

相关标签: C#,WinForm,Excel