截取项目示例中的一部分核心代码
//——————————————————————————————核心代码部分
this.toolStripProgressBar1.Maximum = this.dataGridView1.Rows.Count-1;
Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application();
Microsoft.Office.Interop.Excel.Workbook excelworkbook = excel.Application.Workbooks.Add(true);
excel.Visible = false;//是否显示excel文本
try
{
//异步执行,保证前台窗口程序无卡顿
await Task.Run(() =>
{
for (int i = 0; i < this.dataGridView1.Columns.Count; i++)//复制表格的列头
{
excel.Cells[1, i + 1] = this.dataGridView1.Columns[i].HeaderText;//excel对象的行列索引是从1开始的
//datagridview的行列索引是从0开始的
}
for (int i = 0; i < this.dataGridView1.Rows.Count-1; i++)//减去列头的一行
{
for (int j = 0; j < this.dataGridView1.Columns.Count; j++)
{
if(this.dataGridView1.Rows[i + 1].Cells[j].Value==null)
{
excel.Cells[i + 2, j + 1] ="‘ ";//当表格的单元格为空时,保留行并跳过
break;
}
else if (this.dataGridView1.Rows[i + 1].Cells[j].ValueType == typeof(string))
{
excel.Cells[i + 2, j + 1] = "‘" + this.dataGridView1.Rows[i + 1].Cells[j].Value.ToString();
}
else
{
excel.Cells[i + 2, j + 1] = this.dataGridView1.Rows[i + 1].Cells[j].Value.ToString();
}
}
this.toolStripProgressBar1.Value++;//进度条前进
}
});
}
catch (Exception ex)
{
}
finally
{
//保存xls表格
excelworkbook.SaveAs("111.xls", Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlShared, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
//释放资源
if(excelworkbook!=null)
excelworkbook.Close(Missing.Value, Missing.Value, Missing.Value);
if (excel != null)
{
excel.Workbooks.Close();
excel.Quit();
}
//——————————————————————后续代码非核心代码
主要是两个注意的点
①Microsoft.Office.Interop.Excel.Application对象excel的行列索引是从1开始,和datagridview从0开始索引区别开来,②如果datagirdview单元的值是string类型时,后面加个 ‘ 开发时需要的Microsoft.Office.Interop.Excel.dll组件http://pan.baidu.com/s/1jGrPHrS