c# - 如何将gridview导出到excel
问题描述
我为在 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 中。
解决方案
你应该使用类Excel.Application
。
您正在尝试实例化Excel._Application
不可能的接口。
推荐阅读
- angular - 如何验证年份的 Angular 材料表单字段
- javascript - Vue Typescript 等待承诺
- python - CNN AlexNet 卷积层
- python - 用于网络抓取的 Python POST 请求
- python-3.x - 如何安全地将 API 凭据传递到托管我的 python 脚本的远程 Heroku 服务器?
- javascript - 如何构建一个可以在网页中附加组件的chrome扩展,类似于八叉树?
- javascript - 如何确定音频文件扩展名可能是什么(Chrome、Android)?
- node.js - electron/nodejs 读取快捷方式文件 (lnk)
- tkinter - 在 tkinter - 我如何使用按钮调用函数并输出到 GUI?
- python-3.x - Python类,属性错误,虽然属性存在