用Microsoft将数据导出
用Microsoft将数据导出,首先要添加两个引用:
Microsoft.Office.Interop.Excel
System.Windows.Forms
添加了这两个引用之后就可以写导出了,
导出只要这几个步骤:
1、创建一个Excel运行坏境
2、创建工作簿
3、设置表格
4、导出路径(文件保存路径)
public void Export()
{
try
{
//条件获取数据
var list = Commodity;
#region 导出
//(1)创建一个Excel运行环境
Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();
//(2)创建Excel中的工作薄(只读)
Workbook excelWB = excelApp.Workbooks.Add(Type.Missing);
//(3)创建Excel工作薄中的页sheet (1表示在子表sheet1里进行数据导出)
Worksheet sheet = (Worksheet)excelWB.Worksheets[1];
//将单元格设置为文本格式
sheet.Cells.NumberFormat = "@";
//表头1(第一行)
string dtime = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
sheet.Cells[1, 9] = "商品信息" + dtime;
//表头2(第二行)
sheet.Cells[2, 1] = "商品编号";
sheet.Cells[2, 2] = "商品名称";
sheet.Cells[2, 3] = "商品类别";
sheet.Cells[2, 4] = "单位";
sheet.Cells[2, 5] = "产品规格";
sheet.Cells[2, 6] = "最低库存";
sheet.Cells[2,