c# winform如何将数据存到指定excel表,并实时显示

如题所述

补充和小技巧:
using Excel = Microsoft.Office.Interop.Excel; // 简化命名空间

在窗体事件中执行:
var xlsApp = new Excel.Application();
var wb = xlsApp.Workbooks.Add();
var sh = wb.ActiveSheet as Excel.Worksheet;
sh.Range["A1"].Value = "C# -> Excel 示例";

for (int row = 2; row <= 10; row++)
{
for (int col = 1; col <= 10; col++)
{
sh.Cells[RowIndex: row, ColumnIndex: col].Value = string.Format("{0}, {1}", row, col);
}
}
// 保存文件到 C 盘,请根据自己的 Excel 版本确定 FileFormat
// sh.SaveAs(Filename: "C:\\test.xls", FileFormat: Excel.XlFileFormat.xlExcel12);
xlsApp.Visible = true;
// xlsApp.Quit();
温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2016-05-25
//建立Excel对象
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
excel.Application.Workbooks.Add(true);
后面可以参考
//生成字段名称
for (int i = 0; i < DGVCustomer.ColumnCount; i++)
{
excel.Cells[1, i + 1] = DGVCustomer.Columns[i].HeaderText;
}
//填充数据
for (int i = 0; i < DGVCustomer.RowCount - 1; i++)
{
for (int j = 0; j < DGVCustomer.ColumnCount; j++)
{
if (DGVCustomer[j, i].Value == typeof(string))
{
excel.Cells[i + 2, j + 1] = "" + DGVCustomer[i, j].Value.ToString();
}
else
{
excel.Cells[i + 2, j + 1] = DGVCustomer[j, i].Value.ToString();
}
}
}
excel.Visible = true;本回答被提问者采纳
相似回答