标签:style blog class code java color
必须:添加引用“using Excel = Microsoft.Office.Interop.Excel;”(手动添加引用:右键--添加引用--。net--excel)
关键:创建Excel各个对象模型
private Excel.Application excel;
//Excel的当前工作环境
private
Excel.Workbook workbook;
//Excel的工作簿
private
Excel.Worksheet sheet;
//Excel的工作表(sheet)
private
Excel.Range cell;
//Excel的单元格(range)
private object
obj = Type.Missing;
实例:
(1)新建Excel,并写入数据
public void CreateAndWrite() { Excel.Application excelApp = new Excel.Application(); Excel.Workbook excelWb = excelApp.Workbooks.Add(true); Excel.Worksheet excelSheet = excelWb.ActiveSheet; excelApp.Visible = true; //使Excel可见 //直接写入数据 excelSheet.Cells[1, 1] = "第一行 第一例"; excelSheet.Cells[1, 2] = "第一行 第二列"; excelSheet.Cells[2, 1] = "第二行 第一例"; excelSheet.Cells[2, 2] = "第二行 第二列"; excelSheet.get_Range("A1", "B1").Font.Bold = true; //控制字体加粗 excelSheet.get_Range("A1", "B1").VerticalAlignment = Excel.XlVAlign.xlVAlignCenter; //居中控制 //批量写入数据 string[] dd = new string[10];//模拟数据 string[,] data=new string[10,5];//模拟数据 for (int i = 0; i < 10; i++) { dd[i] = "data" + i; for (int j = 0; j < 5; j++) { data[i, j] = "Data[" + i + "," + j + "]"; } } //1行5列 excelSheet.get_Range("D2", Type.Missing).get_Resize(1, 5).Value = dd; //10行5列 excelSheet.get_Range("D4").get_Resize(10,5).Value = data; //保存(设置Visible=false) excelWb.Save(); //释放资源 System.Runtime.InteropServices.Marshal.ReleaseComObject(excelSheet); excelWb.Close(Type.Missing, Type.Missing, Type.Missing); System.Runtime.InteropServices.Marshal.ReleaseComObject(excelWb); excelApp.Quit(); System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp); }
(2) (写ing....)
标签:style blog class code java color
原文地址:http://www.cnblogs.com/net-study/p/3712137.html