【问题标题】:How to export gridview to excel如何将gridview导出到excel
【发布时间】:2019-08-09 16:04:15
【问题描述】:

我为在 button_click 事件上将 datagridview 导出到 excel 而编写的代码有问题。 错误

无法创建抽象类或接口“Microsoft.Office.Interop.Excel._Application”的实例

显示在这行代码

new Microsoft.Office.Interop.Excel._Application();

参考中的对象库是 microsoft excel 14.0 对象库。我正在使用 VS Ultimate 2013。Ms Office 是 2010

Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel._Application();
Microsoft.Office.Interop.Excel.Workbook workbook = app.Workbooks.Add(Type.Missing);
Microsoft.Office.Interop.Excel.Worksheet Worksheet = null;
Worksheet = workbook.Sheets["Sheet1"];
Worksheet = workbook.ActiveSheet;
Worksheet.Name = "StudentDetail";
for (int i=1; i < dataGridView1.Columns.Count+1; i++ )
{
    Worksheet.Cells[1, i] = dataGridView1.Columns[i - 1].HeaderText;
}
for (int i=0; i < dataGridView1.Rows.Count; i++ )
{
  for (int j=1; j <dataGridView1.Columns.Count; j++ )
  {
      Worksheet.Cells[i + 2, j + 1] = dataGridView1.Rows[i].Cells[j].Value.ToString();
  }

}
var saveFileDialogue = new SaveFileDialog();
saveFileDialogue.FileName = "Output";
saveFileDialogue.DefaultExt = ".xlsx";
if(saveFileDialogue.ShowDialog()==DialogResult.OK)
{
    workbook.SaveAs(saveFileDialogue.FileName, Type.Missing,Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing,Type.Missing);
}
app.Quit();

我希望能成功地将 datagrivew 导出到 excel。

【问题讨论】:

    标签: c# excel


    【解决方案1】:

    您应该使用Excel.Application

    您正在尝试实例化接口Excel._Application,这是不可能的。

    【讨论】:

    • 谢谢彼得,错误已解决,但注意到这行代码有另一个错误:Worksheet.Cells[i + 2, j + 1] = dataGridView1.Rows[i].Cells[j] .Value.ToString();错误是:对象引用未设置为对象的实例
    • 要更改单元格的内容,您必须使用以下内容:Worksheet.Cells[i + 2, j + 1].Value = .....
    • 我已经这样做了,但错误仍然存​​在。我就是这样做的: Worksheet.Cells[i + 2, j + 1].Value = dataGridView1.Rows[i].Cells[j].Value.ToString();
    猜你喜欢
    • 2013-09-25
    • 2014-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-19
    相关资源
    最近更新 更多