如何在c#中创建最多包含30张表格的excel表格

本文关键字:表格 30张 包含 excel 创建 | 更新日期: 2023-09-27 18:29:58

我想从数据表中创建excel,并且想创建最多25张表(当月每天,不包括周末、周六、周日和银行假日),我们如何通过获取月份和数据表中总天数的数组字符串来实现这一点。

Public static void CreateExcel_TabNameUnique( DataTable dt1,string ExcelFilePath, string Tab_Name1)
 {
   try
   {
       runDate = DateTime.Today;
       currMonth = DateTime.Today;
       object missing = Type.Missing;
       Excel.Application oXL = new Excel.Application();
       oXL.Visible = false;
       Excel.Workbook oWB = oXL.Workbooks.Add(missing);
       Excel.Worksheet oSheet = oWB.ActiveSheet as Excel.Worksheet;
       oSheet.Name = Tab_Name1;
       // column headings
       for (int i = 0; i < dt1.Columns.Count; i++)
       {
           oSheet.Cells[1, (i + 1)] = dt1.Columns[i].ColumnName;
       }
       // rows
       for (int i = 0; i < dt1.Rows.Count; i++)
       {
           for (int j = 0; j < dt1.Columns.Count; j++)
           {
               oSheet.Cells[(i + 2), (j + 1)] = dt1.Rows[i][j];
           }
       }
       if (ExcelFilePath != null && ExcelFilePath != "")
       {
           try
           {
               oWB.SaveAs(ExcelFilePath, Excel.XlFileFormat.xlOpenXMLWorkbook,
           missing, missing, missing, missing,
           Excel.XlSaveAsAccessMode.xlNoChange,
           missing, missing, missing, missing, missing);
               oWB.Close(missing, missing, missing);
               oXL.UserControl = true;
               oXL.Quit();
           }
           catch (Exception ex)
           {
           }
       }
   }
   catch (Exception ex)
   {
   } 

}

如何在c#中创建最多包含30张表格的excel表格

很抱歉目前无法验证(Excel Interop有问题…),但从您的评论来看,我认为您的问题只是添加了第二个工作表。你应该能够做到这一点:

Excel.Worksheet secondWorkSheet = oWB.Worksheets.Add();

然后继续操作工作表,就像您在发布的代码中所做的那样。