【发布时间】:2011-03-03 10:05:04
【问题描述】:
我在寡妇应用程序中有数据网格视图,我添加了将数据导出到 Excel 工作表的按钮,但这些出现了
Cannot implicitly convert type 'object' to 'Microsoft.Office.Interop.Excel._Worksheet'. An explicit conversion exists (are you missing a cast?) here ( worksheet = workbook.Sheets["Sheet1"];)
这里出现了这个错误(“SaveAs”方法没有重载需要“11”个参数)
workbook.SaveAs("c:\\output.xls", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing)
这个错误出现了
我的代码:
Old format or invalid type library. (Exception from HRESULT: 0x80028018 (TYPE_E_INVDATAREAD)
private void button1_Click(object sender, EventArgs e)
{
// creating Excel Application
Microsoft.Office.Interop.Excel._Application app = new Microsoft.Office.Interop.Excel.Application();
// creating new WorkBook within Excel application
Microsoft.Office.Interop.Excel._Workbook workbook = app.Workbooks.Add(Type.Missing);
// creating new Excelsheet in workbook
Microsoft.Office.Interop.Excel._Worksheet worksheet = null;
// see the excel sheet behind the program
app.Visible = true;
// get the reference of first sheet. By default its name is Sheet1.
// store its reference to worksheet
worksheet = workbook.Sheets["Sheet1"];
worksheet = workbook.ActiveSheet;
// changing the name of active sheet
worksheet.Name = "Exported from gridview";
// storing header part in Excel
for (int i = 1; i < DGData.Columns.Count + 1; i++)
{
worksheet.Cells[1, i] = DGData.Columns[i - 1].HeaderText;
}
// storing Each row and column value to excel sheet
for (int i = 0; i < DGData.Rows.Count - 1; i++)
{
for (int j = 0; j < DGData.Columns.Count; j++)
{
worksheet.Cells[i + 2, j + 1] = DGData.Rows[i].Cells[j].Value.ToString();
}
}
// save the application
workbook.SaveAs("c:\\output.xls", Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
// Exit from the application
app.Quit();
// storing Each row and column value to excel sheet
for (int i = 0; i < DGData.Rows.Count - 1; i++)
{
for (int j = 0; j < DGData.Columns.Count; j++)
{
worksheet.Cells[i + 2, j + 1] = DGData.Rows[i].Cells[j].Value.ToString();
}
}
}
【问题讨论】:
-
您不应该使用 Office Interop 来根据 Microsoft 的建议从 Web 应用程序生成 excel,无论是出于法律原因还是线程原因。请改用 epplus.codeplex.com 之类的托管方式。
标签: c# excel datagridview