C#把二维数组中的指定数据存储到EXCEL指定位置5
发布网友
发布时间:2023-10-25 06:37
我来回答
共1个回答
热心网友
时间:2024-12-03 13:14
private void writeExcel()
{
#region 初始化Excel表
Excel.Application app = new Excel.Application();
object MissingValue = Type.Missing;
Excel.Workbook wb = app.Workbooks.Add(true);
Excel.Worksheet ws = null;
app.DisplayAlerts = false;
app.AlertBeforeOverwriting = false;
ws = (Excel.Worksheet)wb.Sheets["Sheet1"];
#endregion
#region 填充数据
Object[,] dataArray = new Object[1 + write.Rows.Count, write.Columns.Count];
for (int i = 0; i < write.Columns.Count; i++)//填写列名
{
dataArray[0, i] = write.Columns[i].ColumnName;
for (int j = 0; j < write.Rows.Count; j++)//填入数据
{
dataArray[j + 1, i] = write.Rows[j][i].ToString();
}
}
Excel.Range range = ws.Range[ws.Cells[1, 1], ws.Cells[1 + write.Rows.Count, write.Columns.Count]];
range.Value2 = dataArray;
range.EntireColumn.AutoFit(); //自动设置列宽
range.EntireRow.AutoFit(); //自动设置行高
wb.Saved = true;
wb.SaveCopyAs(path);//保存
app.Quit();//关闭进程
//关闭EXCEL进程
app = null;
wb = null;
ws = null;
GC.Collect();
MessageBox.Show("Excel导出完成");
}
代码中的write是datatable,你改为arraylist就可以了