本文實例為大家分享了Winform實現導入導出Excel文件的具體代碼,供大家參考,具體內容如下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
|
/// <summary> /// 導出Excel文件 /// </summary> /// /// <param name="dataSet"></param> /// <param name="dataTable">數據集</param> /// <param name="isShowExcle">導出后是否打開文件</param> /// <returns></returns> public static bool DataTableToExcel( string filePath, System.Data.DataTable dataTable, bool isShowExcle) { //System.Data.DataTable dataTable = dataSet.Tables[0]; int rowNumber = dataTable.Rows.Count; int columnNumber = dataTable.Columns.Count; int colIndex = 0; if (rowNumber == 0) { return false ; } Microsoft.Office.Interop.Excel.Application excel = new Microsoft.Office.Interop.Excel.Application(); Microsoft.Office.Interop.Excel.Workbook workbook = excel.Workbooks.Add(Microsoft.Office.Interop.Excel.XlWBATemplate.xlWBATWorksheet); Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)workbook.Worksheets[1]; excel.Visible = isShowExcle; Microsoft.Office.Interop.Excel.Range range; foreach (DataColumn col in dataTable.Columns) { colIndex++; excel.Cells[1, colIndex] = col.ColumnName; } object [,] objData = new object [rowNumber, columnNumber]; for ( int r = 0; r < rowNumber; r++) { for ( int c = 0; c < columnNumber; c++) { objData[r, c] =dataTable.Rows[r][c]; } } range = worksheet.get_Range(excel.Cells[2, 1], excel.Cells[rowNumber + 1, columnNumber]); range.Value2 = objData; range.NumberFormatLocal = "@" ; worksheet.SaveAs(filePath, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); //excel.Quit(); return true ; } |
讀取Excel文件數據到DataTable
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
|
/// <summary> /// 讀取Excel文件數據到DataTable /// </summary> /// <param name="filePath">Excel文件路徑</param> private void Import_Excel( string filePath) { string sqlconn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties='Excel 8.0;HDR=False;IMEX=1'" ; string sql = @"select * from [Sheet1$]" ; try { using (OleDbConnection conn = new OleDbConnection(sqlconn)) { using (OleDbDataAdapter adapter = new OleDbDataAdapter(sql, conn)) { System.Data.DataTable dt = new System.Data.DataTable(); adapter.Fill(dt); this .LoadDataGridView(dt); } } } catch (Exception ex) { MessageBox.Show( "打開文件出錯,錯誤信息:" + ex.Message.ToString(), "提示" ); } } |
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/pp_fzp/article/details/51502233