我正在尝试使用数据表从SQL Server生成Excel电子表格。我没有得到任何错误信息,但当我试图保存工作簿时,它没有显示在我的计算机上。我使用以下代码:
using (ExcelEngine excelEngine = new ExcelEngine())
{
//Initialize application
IApplication application = excelEngine.Excel;
//Set the default application version as Excel 2016
application.DefaultVersion = ExcelVersion.Excel2016;
//Create a new workbook
IWorkbook workbook = application.Workbooks.Create(1);
//Access first worksheet from the workbook instance
IWorksheet worksheet = workbook.Worksheets[0];
//Export DataTable to worksheet
//Get data from DataTable
//DataTable dataTable = GetDataTable();
////Export DataTable to worksheet with column name and start range
connection.Open();
SqlCommand cmd = new SqlCommand(PHLIP251, connection);
PHLIP251Datatable.Load(cmd.ExecuteReader());
worksheet.ImportDataTable(PHLIP251Datatable, true, 1, 1);
worksheet.UsedRange.AutofitColumns();
//Save the workbook to disk in xlsx format
workbook.SaveAs(@"Documents\" + "DMBErrors.xlsx");
connection.Close();
生成的Excel文件将位于在示例的bin->Debug文件夹中创建的Documents文件夹中。请在运行时使用下面的代码片段来获取文件的位置。
System.IO.Path.GetFullPath(@"Documents\" + "DMBErrors.xlsx");