c# 操作Excel

//新建excel文件,编辑、格式化、保存
1
Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
2 Workbook workbook = app.Workbooks.Add(true);
3 Worksheet sheet = (Worksheet)workbook.Worksheets["sheet1"];
4 sheet = (Worksheet)workbook.Worksheets.Add(Type.Missing, workbook.Worksheets[1], 1, Type.Missing);
5 sheet.Activate();
6
7 //填充数据
8 sheet.Cells[1, 1] = "序号";
9 sheet.Cells[1, 2] = "道路编码";
10 sheet.Cells[1, 3] = "起始节点";
11 sheet.Cells[1, 4] = "结束节点";
12 for (int i = 0; i < relations.Count; i++)
13 {
14 Relation r = relations[i];
15 sheet.Cells[2 + i, 1] = r.index;
16 sheet.Cells[2 + i, 2] = r.roadNo;
17 sheet.Cells[2 + i, 3] = r.fromPointNo;
18 sheet.Cells[2 + i, 4] = r.toPointNo;
19 }
20
21 //自动调整列宽
22 sheet.Columns.AutoFit();
23
24 //单元格添加边框
25 Range range = sheet.get_Range(sheet.Cells[1, 1], sheet.Cells[relations.Count+1, 4]);
26 range.BorderAround(XlLineStyle.xlContinuous, XlBorderWeight.xlThick, XlColorIndex.xlColorIndexAutomatic, System.Drawing.Color.Black.ToArgb());
27 range.Borders.LineStyle = 1;
28
29 //第一行加粗并居中显示
30 Range rangeHead = sheet.get_Range(sheet.Cells[1, 1], sheet.Cells[1,4]);
31 rangeHead.HorizontalAlignment = XlHAlign.xlHAlignCenter;
32 rangeHead.Font.Bold = true;
33
34 app.Visible = false;
35 app.DisplayAlerts = false;
36 workbook.Close(true, filePath, null);
37 object missing = System.Reflection.Missing.Value;
38 sheet = null;
39 workbook = null;
40 app.Quit();
41 System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
42 app = null;
43 GC.Collect();
posted @ 2012-02-15 15:09  因是因非  阅读(321)  评论(0编辑  收藏  举报