工作中需要将数据库获得的数据导出到Excel中,现记录一些操作Excel的基本语句。
运行环境:VS2012
导入Microsoft.Office.Interop.Excel
1.新建excel
Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
//Microsoft.Office.Interop.Excel.Workbooks workbooks;
Microsoft.Office.Interop.Excel.Workbook workbook = app.Workbooks.Add(true);
//Microsoft.Office.Interop.Excel.Worksheets worksheets;
Microsoft.Office.Interop.Excel.Worksheet worksheet = wb.ActiveSheet;
//如需添加多sheet,用下面这句:
//Microsoft.Office.Interop.Excel.Worksheet worksheet = wb.Worksheets.Add(Type.Missing, Type.Missing, Type.Missing, Type.Missing);
2.设置单元格格式
workseet.Cells.NumberFormatLocal = "@";//设置所有单元格为文本格式
workseet.Columns.AutoFit();//所有列宽自适应
还有一种单元格成文本格式的方式是在需要存放的数据前加上单引号,但这样导出的数据看起来是没问题,但其内容真实数据是带有单引号的,后期数据处理有点不便。
3.单元格赋值
workseet .Cells[row,col] = value;
4.选择范围
//获取单列,先获取单元格再获取整列
//Range firstColumn = workseet.get_Range("A1");不建议使用get_Range方法,已替换为使用Range
Range firstColumn = workseet.Range["A1"];
firstColumn.EntireColumn.AutoFit();//单列宽度自适应
firstColumn.EntireColumn.NumberFormatLocal = "@";//单列格式为文本
使用get_Range报出错误信息:object未包含get_Range的定义,MSDN上已经建议使用Range属性。
在实际使用Range属性时,下面这句代码报错误信息:HRESULT:0x800A03EC
Microsoft.Office.Interop.Excel.Range column = ws.Range[ws.Cells[1, 1]];//报错
column.EntireColumn.NumberFormatLocal = "@";
改成:
Microsoft.Office.Interop.Excel.Range column = ws.Range[ws.Cells[1, 1],ws.Cells[1, 1]];//通过
暂时也没想明白是为什么,Range[cell1,cell2]中的cell2是可选的,不给按道理应该也是可以通过的,但就是报错,整不明白了。
5.合并单元格
workseet.Range[ws.Cells[1, 1], ws.Cells[2, 1]].Merge(Type.Missing);
6.保存Excel
//excel文件另存为,localFilePath为文件保存在本地的路径
workbook.SaveAs(localFilePath,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Type.Missing,Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Type.Missing,Type.Missing, Type.Missing, Type.Missing, Type.Missing);
//清除excel缓存
workbook.Close();
workbook= null;
//垃圾回收
GC.Collect();
7.打开创建的excel
System.Diagnostics.Process.Start(localFilePath);//调用默认应用程序打开