C#操作excel(多种方法比较)
2010-09-30 22:37:59 来源:WEB开发网excel宏操作,sheet和单元格操作:
1 /// <summary>
2 /// 讀取excel數據和插入公式
3 /// </summary>
4 /// <param name="sender"></param>
5 /// <param name="e"></param>
6 protected void Button2_Click(object sender, EventArgs e)
7 {
8 DateTime t1 = DateTime.Now;
9 Response.Write("<br>start time:" + t1.ToString());
10 Excel.Application excelkk = new Excel.Application();
11
12 excelkk.Workbooks.Add(true);
13 int row = 2;
14 DataTable myTable = ds.Tables["[Sheet1$]"];
15 for (int i = 0; i < myTable.Columns.Count; i++)
16 {
17 excelkk.Cells[1, 1 + i] = myTable.Columns[i].ColumnName.ToString();
18 }
19 for (int i = 0; i < myTable.Rows.Count; i++)
20 {
21 for (int j = 0; j < myTable.Columns.Count; j++)
22 {
23 excelkk.Cells[row, j + 1] = myTable.Rows[i][j].ToString();
24 }
25
26 row++;
27 }
28
29
30 //取得特定單元格的值
31 excelkk.Visible = true;
32 this.TextBoxChange.Text = excelkk.get_Range("A2", Type.Missing).Text.ToString();
33 //表的單元格合并
34 Excel.Range range1 = excelkk.get_Range("A2", "D4");
35 range1.Merge(Type.Missing);
36
37
38
39
40 //想表格中插入求和的值
41 Excel.Range range2 = excelkk.get_Range("B25", Type.Missing);
42 range2.Formula = "=SUM(B2:B24)";
43 range2.Calculate();
44
45 //進行宏的循環應用與單元格的刪除和添加,多個單元格默認宏自動操作。
46 Excel.Range range3 = excelkk.get_Range("B25","E25");
47 range2.AutoFill(range3,Excel.XlAutoFillType.xlFillDefault);
48 //刪除表的指定行數操作
49 Excel.Range range7 = null;
50 range7 = excelkk.get_Range(excelkk.Cells[2, 2], excelkk.Cells[4, 4]);
51 range7.Select();
52 range7.EntireRow.Delete(Excel.XlDirection.xlUp);
53
54 //獲取最大用過的行數
55 Excel.Worksheet wsheet1 = (Excel.Worksheet)excelkk.Worksheets.get_Item(1);
56 int n =wsheet1.UsedRange.Cells.Columns.Count;
57 Response.Write(n.ToString() + "<br>");
58 //MessageBox.Show(n.ToString());
59 n = wsheet1.UsedRange.Cells.Rows.Count;
60 Response.Write(n.ToString() + "<br>");
61 //MessageBox.Show(n.ToString());
62 //數據的複製
63 Excel.Range range4 = excelkk.get_Range("A2", "B25");
64 Excel.Range range5 = excelkk.get_Range("E3", "F25");
65 //range4.get_Offset(1,4).Select();
66 range4.Copy(range5);
67 //停用警告信息
68 excelkk.DisplayAlerts = false;
69 GC.Collect();
70
71 }
72
73
74 單個sheet里求和:
75 Excel.Range range2 = excelkk.get_Range("B25", Type.Missing);
76 range2.Formula = "=SUM(B2:B24)";
77 range2.Calculate();
78
79 跨sheet求和:
80 Excel.Worksheet wsheet1 = (Excel.Worksheet)excelSql.Worksheets.get_Item(1);
81 Excel.Range range3 =wsheet1.get_Range("A23", Type.Missing);
82 range3.Formula = "=Sheet3!B8+Sheet3!B12";
83 range3.Calculate();
84
虽然我们拥有强大的NPOI,不过我还是写出来,希望对大家理解office有一定的用处。
更多精彩
赞助商链接