C#操作Excel

  C#操作Excel,需要在引用中添加引用:Microsoft.Office.Interop.Excel,版本12.0.0.0。

  新建Excel对象(Microsoft.Office.Interop.Excel.Application)excel,。调用excel.Application.Workbooks.Add(true)方法。现在既可以向excel中写值。例如: excel.cells[1,1] = 1;即在excel对象的“A1”位置写入了“1”。此时值得注意的是,excel的cell属性,索引必须从1开始,而不是0。(今天在项目中写错了,搞了半天愣是没发现,狂郁闷~)。

  下面给出一些常用操作Excel的代码示例:

private Excel.Application excelApp = new Excel.ApplicationClass();
private Excel.Workbook book = excelApp.Workbooks.Open(fileName, miss, miss, miss, miss, miss,miss, miss, miss, miss, miss, miss, miss, miss, miss);
private Excel.Worksheet sheet = (Excel.Worksheet)excelApp.ActiveSheet;
private Excel.Range range;
range = sheet.get_Range((object)"1", Missing.Value);//获取A1位置
sheet.Cells[1, 1] = "Excel单元格赋值";//Excel单元格赋值     
range.Font.Size = 15;//设置字体大小
range.Font.Underline=true;//设置字体是否有下划线
range.Font.Name="黑体"; //设置字体的种类
range.HorizontalAlignment=XlHAlign.xlHAlignCenter;//设置字体在单元格内的对其方式
range.ColumnWidth=15;//设置单元格的宽度
range.Cells.Interior.Color=System.Drawing.Color.FromArgb(255,204,153).ToArgb();//设置单元格的背景色
range.Borders.LineStyle=1;//设置单元格边框的粗细
range.BorderAround(XlLineStyle.xlContinuous,XlBorderWeight.xlThick,XlColorIndex.xlColorIndexAutomatic,System.Drawing.Color.Black.ToArgb());//给单元格加边框
range.EntireColumn.AutoFit();//自动调整列宽
Range.HorizontalAlignment= xlCenter;// 文本水平居中方式
Range.VerticalAlignment= xlCenter;//文本垂直居中方式
Range.WrapText=true;//文本自动换行
Range.Interior.ColorIndex=39;//填充颜色为淡紫色
Range.Font.Color=clBlue;//字体颜色
excelApp.DisplayAlerts=false;//保存Excel的时候,不弹出是否保存的窗口直接进行保存
book.SaveCopyAs(temp);//填入完信息之后另存到路径及文件名字

  

posted @ 2011-02-28 21:49  BigPei  阅读(364)  评论(0编辑  收藏  举报