我有一个两个表,我必须将信息转储到Excel中。我使用了以下代码。但我得到错误“索引超出范围”。
public void ConvertToTable()
{
DataSet ds = new DataSet();
DataTable dt1 = new DataTable();
DataTable dt2 = new DataTable();
dt1 = ExportToExcel.ToDataTable<CMInfo>(CMInfo);
dt2 = ExportToExcel.ToDataTable<RefMInfo>(REFMINFO);
dt1.TableName = "Changed Method Information";
dt2.TableName = "Referenced Method Information";
ds.Tables.Add(dt1);
ds.Tables.Add(dt2);
Excel.Application xlApp;
Excel.Workbook xlWorkBook;
Excel.Worksheet[] xlWorkSheet = new Excel.Worksheet[ds.Tables.Count];
int Sheet_Count = 0;
object misValue = System.Reflection.Missing.Value;
xlApp = new Excel.Application();
xlApp.SheetsInNewWorkbook = ds.Tables.Count;
xlWorkBook = xlApp.Workbooks.Add(misValue);
foreach (DataTable dt in ds.Tables)
{
if (Sheet_Count < ds.Tables.Count)
{
xlWorkSheet[Sheet_Count] = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(Sheet_Count + 1);
xlWorkSheet[Sheet_Count].Name = dt.TableName;
int iCol = 0;
foreach (DataColumn c in dt.Columns)
{
iCol++;
xlWorkSheet[Sheet_Count].Cells[1, iCol] = c.ColumnName;
xlWorkSheet[Sheet_Count].Cells[1, iCol].Font.Bold = true;
}
// For each row of data
int iRow = 0;
foreach (DataRow r in dt.Rows)
{
iRow++;
// Add each row's cell data...
iCol = 0;
foreach (DataColumn c in dt.Columns)
{
iCol++;
xlWorkSheet[Sheet_Count].Cells[iRow + 1, iCol] = r[c.ColumnName];
xlWorkSheet[Sheet_Count].Cells.ColumnWidth = (xlWorkSheet[Sheet_Count].Cells[iRow + 1, iCol].Count() * 50);
}
}
Sheet_Count++;
}
}
xlWorkBook.SaveAs("ReferenceMethodInfo.xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
xlWorkBook.Close(true, misValue, misValue);
xlApp.Quit();
Marshal.ReleaseComObject(xlWorkSheet[Sheet_Count]);
Marshal.ReleaseComObject(xlWorkBook);
Marshal.ReleaseComObject(xlApp);
ds.Clear();
System.Windows.Forms.MessageBox.Show("Exported Completed");
}
//将此列表转换为DataTable
public static class ExportToExcel
{
// remove "this" if not on C# 3.0 / .NET 3.5
public static DataTable ToDataTable<T>(this IList<T> data)
{
PropertyDescriptorCollection props =
TypeDescriptor.GetProperties(typeof(T));
DataTable table = new DataTable();
for (int i = 0; i < props.Count; i++)
{
PropertyDescriptor prop = props[i];
table.Columns.Add(prop.Name, prop.PropertyType);
}
object[] values = new object[props.Count];
foreach (T item in data)
{
for (int i = 0; i < values.Length; i++)
{
values[i] = props[i].GetValue(item);
}
table.Rows.Add(values);
}
return table;
}
}
答案 0 :(得分:0)
很难说在不知道哪个函数或哪个行导致错误的情况下导致错误的原因是什么。
我承认我从未将数据导出到Excel,因此不知道单元格是从零开始索引还是从1开始索引。
我担心您将iRow
和iCol
初始化为零(0),然后在使用前将它们递增(为1)。