[英]Could not file location while importing dataset to Excel in C#?
我有一個數據集,我想將其導入到Excel中,其中許多數據表將等於Excel工作表,請告訴我我做錯了什么。
我的密碼
private void ExportDataSetToExcel(DataSet ds)
{
//Creae an Excel application instance
Excel.Application excelApp = new Excel.Application();
//Create an Excel workbook instance and open it from the predefined location*emphasized text*
Excel.Workbook excelWorkBook = excelApp.Workbooks.Open("C:\\SSRS\\TFSWorkitem.xlsx");
foreach (DataTable table in ds.Tables)
{
//Add a new worksheet to workbook with the Datatable name
Excel.Worksheet excelWorkSheet = excelWorkBook.Sheets.Add();
excelWorkSheet.Name = table.TableName;
for (int i = 1; i < table.Columns.Count + 1; i++)
{
excelWorkSheet.Cells[1, i] = table.Columns[i - 1].ColumnName;
}
for (int j = 0; j < table.Rows.Count; j++)
{
for (int k = 0; k < table.Columns.Count; k++)
{
excelWorkSheet.Cells[j + 2, k + 1] = table.Rows[j].ItemArray[k].ToString();
}
}
}
excelWorkBook.Save();
excelWorkBook.Close();
excelApp.Quit();
}
為了使用open,工作簿必須存在於目錄中;
我建議您使用此代碼:
private void ExportDataSetToExcel(DataSet ds)
{
//Creae an Excel application instance
Excel.Application excelApp = new Excel.Application();
Excel.Workbook excelWorkBook = excelApp.Workbooks.Add();
foreach (DataTable table in ds.Tables)
{
//Add a new worksheet to workbook with the Datatable name
Excel.Worksheet excelWorkSheet = excelWorkBook.Sheets.Add();
excelWorkSheet.Name = table.TableName;
for (int i = 1; i < table.Columns.Count + 1; i++)
{
excelWorkSheet.Cells[1, i] = table.Columns[i - 1].ColumnName;
}
for (int j = 0; j < table.Rows.Count; j++)
{
for (int k = 0; k < table.Columns.Count; k++)
{
excelWorkSheet.Cells[j + 2, k + 1] = table.Rows[j].ItemArray[k].ToString();
}
}
}
//save the Excel workbook
excelWorkBook.Saveas("C:\\SSRS\\TFSWorkitem.xlsx",
Excel.XlSaveAsAccessMode.xlNoChange);
excelWorkBook.Close();
excelApp.Quit();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.