C# 将DataGridView导出到Excel(Microsoft.Office.Interop.Excel)
我试图将datagridview内容导出到Excel,但遇到以下问题 我使用的代码如下(取自code.msdn.microsoft.com)C# 将DataGridView导出到Excel(Microsoft.Office.Interop.Excel),c#,excel,visual-studio,datagridview,C#,Excel,Visual Studio,Datagridview,我试图将datagridview内容导出到Excel,但遇到以下问题 我使用的代码如下(取自code.msdn.microsoft.com) private void ExportToExcel() { //创建Excel对象。 Microsoft.Office.Interop.Excel.\u Application Excel=新的Microsoft.Office.Interop.Excel.Application(); Microsoft.Office.Interop.Excel.\u工作
private void ExportToExcel()
{
//创建Excel对象。
Microsoft.Office.Interop.Excel.\u Application Excel=新的Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.\u工作簿=Excel.Workbooks.Add(Type.Missing);
Microsoft.Office.Interop.Excel.\u工作表=null;
尝试
{
工作表=工作簿.ActiveSheet;
工作表.Name=“ExportedFromDatGrid”;
int-cellRowIndex=1;
int-cellColumnIndex=1;
//循环遍历每行并从每列读取值。
对于(int i=0;i
以前,我从reference manager/COM部分(Microsoft Excel 16.0对象库)将引用Microsoft.Office.Interop.Excel添加到我的项目中。尽管如此,我还是收到了下一条错误消息:
->类型“Office.Interop.Excel”中不存在类型名称\u应用程序
->“Office.Interop.Excel”类型中不存在类型名称\u工作簿
->类型“Office.Interop.Excel”中不存在类型名称\u工作表
我怎样才能解决这个问题
非常感谢 除了缺少网格的第一行/最后一行之外,您发布的代码似乎按预期工作。我运行的是Excel Obj`14 lib,但由于错误似乎来自前三行,您是否尝试过去掉Excel.properties中的“下划线”?没有它,它仍然可以工作。只是一个猜测。对不起,我不明白你说“去掉Excel.properties中的“下划线”是什么意思。下划线就是“u”字符!错误表明“\u应用程序”、“\u工作簿”和“\u工作表”不存在。尝试在不带下划线的情况下将值更改为“应用程序”、“工作簿”和“工作表”。
private void ExportToExcel()
{
// Creating a Excel object.
Microsoft.Office.Interop.Excel._Application excel = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel._Workbook workbook = excel.Workbooks.Add(Type.Missing);
Microsoft.Office.Interop.Excel._Worksheet worksheet = null;
try
{
worksheet = workbook.ActiveSheet;
worksheet.Name = "ExportedFromDatGrid";
int cellRowIndex = 1;
int cellColumnIndex = 1;
//Loop through each row and read value from each column.
for (int i = 0; i < DataGridView1.Rows.Count - 1; i++)
{
for (int j = 0; j < DataGridView1.Columns.Count; j++)
{
// Excel index starts from 1,1. As first Row would have the Column headers, adding a condition check.
if (cellRowIndex == 1)
{
worksheet.Cells[cellRowIndex, cellColumnIndex] = DataGridView1.Columns[j].HeaderText;
}
else
{
worksheet.Cells[cellRowIndex, cellColumnIndex] = DataGridView1.Rows[i].Cells[j].Value.ToString();
}
cellColumnIndex++;
}
cellColumnIndex = 1;
cellRowIndex++;
}
//Getting the location and file name of the excel to save from user.
SaveFileDialog saveDialog = new SaveFileDialog();
saveDialog.Filter = "Excel files (*.xlsx)|*.xlsx|All files (*.*)|*.*";
saveDialog.FilterIndex = 2;
if (saveDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
workbook.SaveAs(saveDialog.FileName);
MessageBox.Show("Export Successful");
}
}
catch (System.Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
excel.Quit();
workbook = null;
excel = null;
}
}