【问题标题】:Could not file location while importing dataset to Excel in C#?在 C# 中将数据集导入 Excel 时无法文件位置?
【发布时间】:2018-07-29 12:55:36
【问题描述】:

我有一个数据集,我想将其导入 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();
}

【问题讨论】:

  • 错误是什么?代码似乎是正确的
  • System.Runtime.InteropServices.COMException:'抱歉,我们找不到 C:\SSRS\TFSWorkitem.xlsx。是否有可能被移动、重命名或删除?'

标签: c# excel dataset


【解决方案1】:

工作簿必须存在于目录中才能使用 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();
    }

【讨论】:

  • name excelworkbook 在当前上下文中不存在。错误
  • 添加这个 Excel.Workbook excelWorkBook = excelApp.Workbooks.add();循环前
猜你喜欢
  • 1970-01-01
  • 2017-01-13
  • 2013-02-06
  • 2011-04-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-02
  • 1970-01-01
相关资源
最近更新 更多