C#多種操作excel的方法比較
我們在做excel資料的時候,通常有以下方法。
一.導入導出excel常用方法:
1.用查詢表的方式查詢並show在數據集控件上。
public static string strCon = " Provider = Microsoft.Jet.OLEDB.4.0 ; Data Source =C:\\08.xls;Extended Properties=Excel 8.0"; public static DataSet ds; protected void Page_Load(object sender, EventArgs e) { OleDbConnection conn = new OleDbConnection(strCon); string sql = "select * from [Sheet1$]"; conn.Open(); OleDbDataAdapter myCommand = new OleDbDataAdapter(sql, strCon); ds = new DataSet(); myCommand.Fill(ds, "[Sheet1$]"); conn.Close(); datagrid1.DataMember = "[Sheet1$]"; datagrid1.DataSource = ds; datagrid1.DataBind(); //Excel.Application excel = new Excel.Application(); //excel.Application.Workbooks.Add(true); //excel.Visible = true; }
2.一個一個單元格的進行插入
string str = @"Data Source=IT-428E4EA4B0C7\SQLEXPRESS;Initial Catalog=TestBase;Integrated Security=True"; SqlConnection conn = new SqlConnection(str); conn.Open(); int n = 0; for (int i = 1; i < 20; i++) { if (n > 3) break; else if (msheet.Cells.get_Range("A" + i, Type.Missing).Text.ToString() == "" && n <= 3) { n++; } else { //循環獲取excel單元格的值一次一次的插入,excuteSql為執行的存儲過程 excuteSql(msheet.Cells.get_Range("B" + i, Type.Missing).Text.ToString(), msheet.Cells.get_Range("B" + (i + 1), Type.Missing).Text.ToString(), msheet.Cells.get_Range("B" + (i + 2), Type.Missing).Text.ToString(), conn); i = i + 3; } } conn.Close();
二快速導入導出
1.我們都知道當向db裡批量插入數據的時候我們會選擇SqlBulkCopy
if (dataTable!=null && dataTable.Rows.Count!=0) { sqlBulkCopy.WriteToServer(dataTable); }
這個可以看 深山老林新發的一篇SQLServer中批量插入數據方式的性能對比
下面是SqlBulkCopy的方法,這個方法有一個弊端就是當excel某一列即有文字,還有日期的時候,會出現null值,我在網上查瞭一些資料說連接字串加上;HDR=YES;IMEX=1’的時候會都當做字符處理,但是還是會出現一些bug,所以建議最好先把excel數據分析到datatable裡然後再用SqlBulkCopy倒入數據庫
// block copy to DB from Excel //By xijun, //step create an excel file C:\Inetpub\wwwroot\test.xls , fill cell(1,1) with "Data",cell(1,2) with "name" //step create table named "Data" with column ("data","name") in your DB //there the code below: DateTime t1 = DateTime.Now; Response.Write("<br>start time:" + t1.ToString()); string ExcelFile = @"C:\\_Hub_Report.xls"; string excelConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + ExcelFile + ";Extended Properties='Excel.0;HDR=YES;IMEX=1'"; using (OleDbConnection excelConnection = new OleDbConnection(excelConnectionString)) { excelConnection.Open(); //Getting source data //非空讀入數據 OleDbCommand command = new OleDbCommand("Select [Region],[CustomerPN],[RMA],[Date],[QTY],[Return/Pull] FROM [_Hub_Report$] ", excelConnection); // Initialize SqlBulkCopy object using (OleDbDataReader dr = command.ExecuteReader()) { // Copy data to destination string sqlConnectionString = @"Data Source=MININT-GPHNA\SQLEXPRESS;Initial Catalog=GDS_Service;Integrated Security=True"; using (SqlBulkCopy bulkCopy = new SqlBulkCopy(sqlConnectionString)) { bulkCopy.DestinationTableName = "GDS_Hub_data"; //加入隻加入一個列的話,那麼就會其他數據庫列都默認為空。 bulkCopy.ColumnMappings.Add("Region", "region"); bulkCopy.ColumnMappings.Add("CustomerPN", "customer_item_number"); bulkCopy.ColumnMappings.Add("RMA", "Rma"); bulkCopy.ColumnMappings.Add("Date", "date"); bulkCopy.ColumnMappings.Add("QTY", "Qty_1"); bulkCopy.ColumnMappings.Add("Return/Pull", "return_pull"); //bcp.BatchSize =;//每次傳輸的行數 //bcp.NotifyAfter =;//進度提示的行數 bulkCopy.BatchSize =; bulkCopy.NotifyAfter =; bulkCopy.WriteToServer((IDataReader)dr); } } //Closing connection excelConnection.Close(); } DateTime t2 = DateTime.Now; Response.Write("<br>End time:" + t2.ToString()); Response.Write("<br>use time:" + ((TimeSpan)(t2 - t1)).Milliseconds.ToString() + " Milliseconds"); Response.Write("<br>inser record count :");
2.快速導出db的數據到excel
這種方法就是利用
Excel.QueryTables
Excel.QueryTable
Querytable把數據快速導入excel裡。我們在做復雜報表的時候,這個用的是比較多瞭,但是單單會這個沒有用,它隻是快速的把db裡的數據放放到excel裡,在做大量數據而且需要設定excel樣式的時候我們會選擇先用這種方法把數據導入excel一個臨時sheet,再利sheet復制,sheet移動,和一些excel樣式設定,以及excel一個強大的自動填充的功能,那麼這些就可以讓我們快速的做出花樣多試的excel報表,當然這個要求我們比較熟練office的操作,包括宏的操作。
public string query_table_getdata(string sourpath) { string str_path = sourpath.Substring(0, sourpath.Length - 22); str_path = str_path + "basic.xls"; Excel.QueryTables m_objQryTables = null; Excel.QueryTable m_objQryTable = null; Excel.Application m_objExcel = null; Excel.Workbooks m_objBooks = null; Excel.Workbook m_objBook = null; Excel.Sheets m_objSheets = null; Excel.Worksheet m_objSheet = null; Excel.Range m_objRange = null; m_objExcel = new Excel.Application(); //try //{ m_objBooks = m_objExcel.Workbooks; m_objBooks.Open(sourpath, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); m_objBook = (Excel.Workbook)m_objBooks.get_Item(1); m_objSheets = (Excel.Sheets)m_objBook.Worksheets; m_objSheet = (Excel.Worksheet)m_objSheets.get_Item(1); m_objRange = m_objSheet.get_Range("A2", Type.Missing); m_objQryTables = m_objSheet.QueryTables; string sqlstr = "SELECT [day01],[day02],[day03],[day04],[day05],[day06],[day07],[day08],[day09],[day10],[day11],[day12],[day13],[day14]"; sqlstr += ",[week01] ,[week02],[week03],[week04],[week05],[week06],[week07],[week08],[week09],[week10],[week11],[week12],[week13],[week14]"; sqlstr += ",[week15],[week16],[week17],[week18],[week19],[week20],[week21],[week22],[week23],[week24]"; sqlstr += " FROM [GDS_Service].[dbo].[GDS_Service_Report_Base] order by groupID ,id"; //可以放在配置文件裡 string conn = @"Provider=SQLOLEDB.1;Data Source=MININT-G87PHNA\SQLEXPRESS;uid=xijun_ke;Password=12345678; Initial Catalog=GDS_Service;Persist Security Info=False;"; m_objQryTable = (Excel.QueryTable)m_objQryTables.Add("OLEDB;" + conn, m_objRange, sqlstr); m_objQryTable.RefreshStyle = Excel.XlCellInsertionMode.xlInsertEntireRows; m_objQryTable.Refresh(false); 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); m_objBook.Close(false, Type.Missing, Type.Missing); //} //catch (Exception ee) //{ // mp.WriteLog(ee.ToString()); //} //finally //{ m_objExcel.Quit(); GC.Collect(); //} return str_path; }
com操作excel的一些特性操作:
range.NumberFormatLocal = "@"; //設置單元格格式為文本 range = (Range)worksheet.get_Range("A1", "E1"); //獲取Excel多個單元格區域:本例做為Excel表頭 range.Merge(0); //單元格合並動作 worksheet.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; //字體顏色 xlsApp.DisplayAlerts=false; //保存Excel的時候,不彈出是否保存的窗口直接進行保存 workbook.SaveCopyAs(temp);/**////填入完信息之後另存到路徑及文件名字
excel宏操作,sheet和單元格操作:
/// <summary> /// 讀取excel數據和插入公式 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void Button2_Click(object sender, EventArgs e) { DateTime t1 = DateTime.Now; Response.Write("<br>start time:" + t1.ToString()); Excel.Application excelkk = new Excel.Application(); excelkk.Workbooks.Add(true); int row = 2; DataTable myTable = ds.Tables["[Sheet1$]"]; for (int i = 0; i < myTable.Columns.Count; i++) { excelkk.Cells[1, 1 + i] = myTable.Columns[i].ColumnName.ToString(); } for (int i = 0; i < myTable.Rows.Count; i++) { for (int j = 0; j < myTable.Columns.Count; j++) { excelkk.Cells[row, j + 1] = myTable.Rows[i][j].ToString(); } row++; } //取得特定單元格的值 excelkk.Visible = true; this.TextBoxChange.Text = excelkk.get_Range("A2", Type.Missing).Text.ToString(); //表的單元格合並 Excel.Range range1 = excelkk.get_Range("A2", "D4"); range1.Merge(Type.Missing); //想表格中插入求和的值 Excel.Range range2 = excelkk.get_Range("B25", Type.Missing); range2.Formula = "=SUM(B2:B24)"; range2.Calculate(); //進行宏的循環應用與單元格的刪除和添加,多個單元格默認宏自動操作。 Excel.Range range3 = excelkk.get_Range("B25","E25"); range2.AutoFill(range3,Excel.XlAutoFillType.xlFillDefault); //刪除表的指定行數操作 Excel.Range range7 = null; range7 = excelkk.get_Range(excelkk.Cells[2, 2], excelkk.Cells[4, 4]); range7.Select(); range7.EntireRow.Delete(Excel.XlDirection.xlUp); //獲取最大用過的行數 Excel.Worksheet wsheet1 = (Excel.Worksheet)excelkk.Worksheets.get_Item(1); int n =wsheet1.UsedRange.Cells.Columns.Count; Response.Write(n.ToString() + "<br>"); //MessageBox.Show(n.ToString()); n = wsheet1.UsedRange.Cells.Rows.Count; Response.Write(n.ToString() + "<br>"); //MessageBox.Show(n.ToString()); //數據的複製 Excel.Range range4 = excelkk.get_Range("A2", "B25"); Excel.Range range5 = excelkk.get_Range("E3", "F25"); //range4.get_Offset(1,4).Select(); range4.Copy(range5); //停用警告信息 excelkk.DisplayAlerts = false; GC.Collect(); } 單個sheet裡求和: Excel.Range range2 = excelkk.get_Range("B25", Type.Missing); range2.Formula = "=SUM(B2:B24)"; range2.Calculate(); 跨sheet求和: Excel.Worksheet wsheet1 = (Excel.Worksheet)excelSql.Worksheets.get_Item(1); Excel.Range range3 =wsheet1.get_Range("A23", Type.Missing); range3.Formula = "=Sheet3!B8+Sheet3!B12"; range3.Calculate();
雖然我們擁有強大的NPOI,不過我還是寫出來,希望對大傢理解office有一定的用處。
以上所述是小編給大傢介紹的C#多種操作excel的方法比較,希望對大傢有所幫助。在此也非常感謝大傢對WalkonNet網站的支持!
推薦閱讀:
- python 使用xlsxwriter循環向excel中插入數據和圖片的操作
- 如何用python合並多個excel文件
- Python在不同場景合並多個Excel的方法
- 詳解Python操作Excel之openpyxl
- python處理excel文件之xlsxwriter 模塊