[英]Error Exporting to Excel C#
将Excel导出到C#时出现错误,我找不到代码错误的地方以及问题的解决方案
错误:
GestãoSI.exe中发生了类型为'System.Runtime.InteropServices.COMException'的未处理异常
附加信息:Índiceinválido。 (HRESULT例外:0x8002000B(DISP_E_BADINDEX))
代码运行时出现错误
// Add a workbook.
oBook = oExcel_12.Workbooks.Add(oMissing);
// Get worksheets collection
oSheetsColl = oExcel_12.Worksheets;
// Get Worksheet "Sheet1"
oSheet = (Excel_12.Worksheet)oSheetsColl.get_Item("Sheet1");
这是我的全部代码
public static void ExportDataGridViewTo_Excel12(DataGridView itemDataGridView)
{
Excel_12.Application oExcel_12 = null; //Excel_12 Application
Excel_12.Workbook oBook = null; // Excel_12 Workbook
Excel_12.Sheets oSheetsColl = null; // Excel_12 Worksheets collection
Excel_12.Worksheet oSheet = null; // Excel_12 Worksheet
Excel_12.Range oRange = null; // Cell or Range in worksheet
Object oMissing = System.Reflection.Missing.Value;
// Create an instance of Excel_12.
oExcel_12 = new Excel_12.Application();
// Make Excel_12 visible to the user.
oExcel_12.Visible = true;
// Set the UserControl property so Excel_12 won't shut down.
oExcel_12.UserControl = true;
// System.Globalization.CultureInfo ci = new System.Globalization.CultureInfo("en-US");
// Add a workbook.
oBook = oExcel_12.Workbooks.Add(oMissing);
// Get worksheets collection
oSheetsColl = oExcel_12.Worksheets;
// Get Worksheet "Sheet1"
oSheet = (Excel_12.Worksheet)oSheetsColl.get_Item("Sheet1");
// Export titles
for (int j = 0; j < itemDataGridView.Columns.Count; j++)
{
oRange = (Excel_12.Range)oSheet.Cells[1, j + 1];
oRange.Value2 = itemDataGridView.Columns[j].HeaderText;
}
// Export data
for (int i = 0; i < itemDataGridView.Rows.Count - 1; i++)
{
for (int j = 0; j < itemDataGridView.Columns.Count; j++)
{
oRange = (Excel_12.Range)oSheet.Cells[i + 2, j + 1];
oRange.Value2 = itemDataGridView[j, i].Value;
}
}
// Release the variables.
//oBook.Close(false, oMissing, oMissing);
oBook = null;
//oExcel_12.Quit();
oExcel_12 = null;
// Collect garbage.
GC.Collect();
}
这项工作对我来说..
oSheet = oBook.Worksheets.get_Item(index);
由于您从Excel获得了非英语的异常文本,因此我假设没有名为“ Sheet1”的工作表,而是具有本地化名称。 您必须使用本地化名称,或者最好使用工作表索引(应以1开头)代替工作表名称,这会更好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.