这是我的代码......
Microsoft.Office.Interop.Excel.Application Excel = new Microsoft.Office.Interop.Excel.Application();
Workbook wb = Excel.Workbooks.Add(XlSheetType.xlWorksheet);
Worksheet ws = (Worksheet)Excel.ActiveSheet;
Excel.Visible = true;
ws.Cells[1, 1] = "ID";
ws.Cells[1, 2] = "Name";
ws.Cells[1, 3] = "Detail";
ws.Cells[1, 4] = "Category";
ws.Cells[1, 5] = "Brand";
ws.Cells[1, 6] = "In Stock";
ws.Cells[1, 7] = "Price";
ws.Cells[1, 8] = "Total";
for (int i = 2; i <= dgDetail.Rows.Count; i++)
{
for (int j = 2; j <= 8; j++)
{
ws.Cells[i, j] = dgDetail.Rows[i - 2].Cells[j - 1].Value;
}
}
答案 0 :(得分:0)
Excel有1,1个基于数组,第一个单元格是1,1,所以当你将“ID”放到这个单元格时就可以了。您的gridview看起来从零开始。 1)你开始从第0行导出dgDetail,我认为是正确的,但是你跳过了最后一行 - 你可以稍微重写你的代码来看看它:
for (int i = 0; i <= dgDetail.Rows.Count-2; i++) {
dgDetail.Rows[i]; //pseudocode
}
也许这就是你计划它的方式,但是你没有导出行dgDetail.Row.Count - 1
2)
for (int j = 2; j <= 8; j++) {
ws.Cells[i, j] = dgDetail.Rows[i - 2].Cells[j - 1].Value;
}
在这里你需要将j的第一个值改为1,因为你从第二列开始,否则:
ws.Cells[i, 2] = dgDetail.Rows[i - 2].Cells[2 - 1].Value;
我猜你只是对基于excel 1,1的数组感到困惑,
此外,如果您有大量的导出,最好在一个操作中编写整个数组:
Range range = worksheet.Range[worksheet.Cells[1, 1], worksheet.Cells[2, 2]];
range.Value = new object[2, 2] { { 1, 2 }, { 3, 4 } };