C#怎么用代码操作excel表

2024-11-15 11:29:36
推荐回答(2个)
回答1:

1.添加DLL文件“Microsoft.Office.Interop.Excel.dll”引用(解决方案资源管理器-右键“添加引用”)
2.命名空间中添加引用using Microsoft.Office.Interop.Excel;
3.填充Excel
private void btnExport_Click(object sender, EventArgs e)
{
Microsoft.Office.Interop.Excel.Application myExcel = new Microsoft.Office.Interop.Excel.Application();
myExcel.Application.Workbooks.Add(true);
//让Excel文件可见
myExcel.Visible = true;
//第一行为报表名称
myExcel.Cells[1, 1] = "房间类型";
myExcel.Cells[1, 2] = "房间号";
myExcel.Cells[1, 3] = "床位数";
myExcel.Cells[1, 4] = "状态";
myExcel.Cells[1, 5] = "价格";
myExcel.Cells[1, 6] = "备注";
int i = 2;
foreach (ListViewItem item in listView1.Items)
{
int j = 1;
foreach (ListViewItem.ListViewSubItem subitem in item.SubItems)
{
myExcel.Cells[i, j] = subitem.Text;
j++;
}
i++;
}
}
------
其实我更推荐NPOI,毕竟那个更专业,你可以搜搜,但看你的需求上面就可以了

回答2:

为什么赋值时是从2,2开始不是2,1呢??????