一聚教程网:一个值得你收藏的教程网站

热门教程

C# WinForm创建Excel文件的实例

时间:2022-06-25 07:56:16 编辑:袖梨 来源:一聚教程网

实例如下:

 

 代码如下复制代码

privateboolcreatExcel(stringxlsfile)

    {

      try

      {

        objectmissing = System.Reflection.Missing.Value;

        Excel.ApplicationClass myExcel =newExcel.ApplicationClass();

 

        Excel._Workbook xBk;       //工作薄

        Excel._Worksheet xSt;  //工作Sheet 

 

        xBk = myExcel.Workbooks.Add(true);

 

        for(inti = 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();

        returntrue;

      }

      catch(Exception ex)

      {

        MessageBox.Show("Excel创建失败!原因:"+ ex.Message);

        returnfalse;

      }

    }

 

热门栏目