C#操作excel(多种方法比较)
2010-09-30 22:37:59 来源:WEB开发网2.快速导出db的数据到excel
这种方法就是利用
Excel.QueryTables
Excel.QueryTable
Querytable把数据快速导入excel里。我们在做复杂报表的时候,这个用的是比较多了,但是单单会这个没有用,它只是快速的把db里的数据放放到excel里,
在做大量数据而且需要设定excel样式的时候我们会选择先用这种方法把数据导入excel一个临时sheet,再利sheet复制,sheet移动,和一些excel样式设定,以及
excel一个强大的自动填充的功能,那么这些就可以让我们快速的做出花样多试的excel报表,当然这个要求我们比较熟练office的操作,包括宏的操作。
1 public string query_table_getdata(string sourpath)
2 {
3 string str_path = sourpath.Substring(0, sourpath.Length - 22);
4 str_path = str_path + "basic.xls";
5
6 Excel.QueryTables m_objQryTables = null;
7 Excel.QueryTable m_objQryTable = null;
8 Excel.Application m_objExcel = null;
9 Excel.Workbooks m_objBooks = null;
10 Excel.Workbook m_objBook = null;
11 Excel.Sheets m_objSheets = null;
12 Excel.Worksheet m_objSheet = null;
13 Excel.Range m_objRange = null;
14 m_objExcel = new Excel.Application();
15
16 //try
17 //{
18 m_objBooks = m_objExcel.Workbooks;
19 m_objBooks.Open(sourpath, Type.Missing, Type.Missing, Type.Missing, Type.Missing,
20 Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
21
22 m_objBook = (Excel.Workbook)m_objBooks.get_Item(1);
23
24
25 m_objSheets = (Excel.Sheets)m_objBook.Worksheets;
26 m_objSheet = (Excel.Worksheet)m_objSheets.get_Item(1);
27 m_objRange = m_objSheet.get_Range("A2", Type.Missing);
28 m_objQryTables = m_objSheet.QueryTables;
29 string sqlstr = "SELECT [day01],[day02],[day03],[day04],[day05],[day06],[day07],[day08],[day09],[day10],[day11],[day12],[day13],[day14]";
30 sqlstr += ",[week01] ,[week02],[week03],[week04],[week05],[week06],[week07],[week08],[week09],[week10],[week11],[week12],[week13],[week14]";
31 sqlstr += ",[week15],[week16],[week17],[week18],[week19],[week20],[week21],[week22],[week23],[week24]";
32 sqlstr += " FROM [GDS_Service].[dbo].[GDS_Service_Report_Base] order by groupID ,id";
33 //可以放在配置文件里
34 string conn = @"Provider=SQLOLEDB.1;Data Source=MININT-G87PHNA\SQLEXPRESS;uid=xijun_ke;Password=12345678;
Initial Catalog=GDS_Service;Persist Security Info=False;";
35
36 m_objQryTable = (Excel.QueryTable)m_objQryTables.Add("OLEDB;" + conn, m_objRange, sqlstr);
37
38 m_objQryTable.RefreshStyle = Excel.XlCellInsertionMode.xlInsertEntireRows;
39
40 m_objQryTable.Refresh(false);
41 m_objBook.SaveAs(str_path, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
42 m_objBook.Close(false, Type.Missing, Type.Missing);
43 //}
44 //catch (Exception ee)
45 //{
46 // mp.WriteLog(ee.ToString());
47 //}
48 //finally
49 //{
50 m_objExcel.Quit();
51 GC.Collect();
52 //}
53 return str_path;
54
55 }
更多精彩
赞助商链接