一.导入导出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 1 create an excel file C:\Inetpub\wwwroot\test.xls , fill cell(1,1) with "Data",cell(1,2) with "name" //step 2 create table named "Data" with 2 column ("data","name") in your DB //there the code below: DateTime t1 = DateTime.Now; Response.Write("<br>start time:" + t1.ToString()); string ExcelFile = @"C:\\20090916_Hub_Report.xls"; string excelConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + ExcelFile + ";Extended Properties='Excel 8.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 [20090916_Hub_Report$] ", excelConnection); // Initialize SqlBulkCopy object using (OleDbDataReader dr = command.ExecuteReader()) { // Copy data to destination string sqlConnectionString = @"Data Source=MININT-G87PHNA\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 = 100;//每次传输的行数 //bcp.NotifyAfter = 100;//进度提示的行数 bulkCopy.BatchSize = 100; bulkCopy.NotifyAfter = 100; 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 :3307");
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();
excel中对于样式的定义和使用
/// <summary> /// 单元格背景色及填充方式 /// </summary> /// <param name="startRow">起始行</param> /// <param name="startColumn">起始列</param> /// <param name="endRow">结束行</param> /// <param name="endColumn">结束列</param> /// <param name="color">颜色索引</param> public void CellsBackColor(int startRow, int startColumn, int endRow, int endColumn, ColorIndex color) { Excel.Range range = myExcel.get_Range(myExcel.Cells[startRow, startColumn], myExcel.Cells[endRow, endColumn]); range.Interior.ColorIndex = color; range.Interior.Pattern = Pattern.Solid; } /// <summary> /// 单元格背景色及填充方式 /// </summary> /// <param name="startRow">起始行</param> /// <param name="startColumn">起始列</param> /// <param name="endRow">结束行</param> /// <param name="endColumn">结束列</param> /// <param name="color">颜色索引</param> /// <param name="pattern">填充方式</param> public void CellsBackColor(int startRow, int startColumn, int endRow, int endColumn, ColorIndex color, Pattern pattern) { Excel.Range range = myExcel.get_Range(myExcel.Cells[startRow, startColumn], myExcel.Cells[endRow, endColumn]); range.Interior.ColorIndex = color; range.Interior.Pattern = pattern; } /// <summary> /// 设置行高 /// </summary> /// <param name="startRow">起始行</param> /// <param name="endRow">结束行</param> /// <param name="height">行高</param> public void SetRowHeight(int startRow, int endRow, int height) { //获取当前正在使用的工作表 Excel.Worksheet worksheet = (Excel.Worksheet)myExcel.ActiveSheet; Excel.Range range = (Excel.Range)worksheet.Rows[startRow.ToString() + ":" + endRow.ToString(), System.Type.Missing]; range.RowHeight = height; } /// <summary> /// 自动调整行高 /// </summary> /// <param name="columnNum">列号</param> public void RowAutoFit(int rowNum) { //获取当前正在使用的工作表 Excel.Worksheet worksheet = (Excel.Worksheet)myExcel.ActiveSheet; Excel.Range range = (Excel.Range)worksheet.Rows[rowNum.ToString() + ":" + rowNum.ToString(), System.Type.Missing]; range.EntireColumn.AutoFit(); } /// <summary> /// 设置列宽 /// </summary> /// <param name="startColumn">起始列(列对应的字母)</param> /// <param name="endColumn">结束列(列对应的字母)</param> /// <param name="width"></param> public void SetColumnWidth(string startColumn, string endColumn, int width) { //获取当前正在使用的工作表 Excel.Worksheet worksheet = (Excel.Worksheet)myExcel.ActiveSheet; Excel.Range range = (Excel.Range)worksheet.Columns[startColumn + ":" + endColumn, System.Type.Missing]; range.ColumnWidth = width; } /// <summary> /// 设置列宽 /// </summary> /// <param name="startColumn">起始列</param> /// <param name="endColumn">结束列</param> /// <param name="width"></param> public void SetColumnWidth(int startColumn, int endColumn, int width) { string strStartColumn = GetColumnName(startColumn); string strEndColumn = GetColumnName(endColumn); //获取当前正在使用的工作表 Excel.Worksheet worksheet = (Excel.Worksheet)myExcel.ActiveSheet; Excel.Range range = (Excel.Range)worksheet.Columns[strStartColumn + ":" + strEndColumn, System.Type.Missing]; range.ColumnWidth = width; } /// <summary> /// 自动调整列宽 /// </summary> /// <param name="columnNum">列号</param> public void ColumnAutoFit(string column) { //获取当前正在使用的工作表 Excel.Worksheet worksheet = (Excel.Worksheet)myExcel.ActiveSheet; Excel.Range range = (Excel.Range)worksheet.Columns[column + ":" + column, System.Type.Missing]; range.EntireColumn.AutoFit(); } /// <summary> /// 自动调整列宽 /// </summary> /// <param name="columnNum">列号</param> public void ColumnAutoFit(int columnNum) { string strcolumnNum = GetColumnName(columnNum); //获取当前正在使用的工作表 Excel.Worksheet worksheet = (Excel.Worksheet)myExcel.ActiveSheet; Excel.Range range = (Excel.Range)worksheet.Columns[strcolumnNum + ":" + strcolumnNum, System.Type.Missing]; range.EntireColumn.AutoFit(); } /// <summary> /// 字体颜色 /// </summary> /// <param name="startRow">起始行</param> /// <param name="startColumn">起始列</param> /// <param name="endRow">结束行</param> /// <param name="endColumn">结束列</param> /// <param name="color">颜色索引</param> public void FontColor(int startRow, int startColumn, int endRow, int endColumn, ColorIndex color) { Excel.Range range = myExcel.get_Range(myExcel.Cells[startRow, startColumn], myExcel.Cells[endRow, endColumn]); range.Font.ColorIndex = color; } /// <summary> /// 字体样式(加粗,斜体,下划线) /// </summary> /// <param name="startRow">起始行</param> /// <param name="startColumn">起始列</param> /// <param name="endRow">结束行</param> /// <param name="endColumn">结束列</param> /// <param name="isBold">是否加粗</param> /// <param name="isItalic">是否斜体</param> /// <param name="underline">下划线类型</param> public void FontStyle(int startRow, int startColumn, int endRow, int endColumn, bool isBold, bool isItalic, UnderlineStyle underline) { Excel.Range range = myExcel.get_Range(myExcel.Cells[startRow, startColumn], myExcel.Cells[endRow, endColumn]); range.Font.Bold = isBold; range.Font.Underline = underline; range.Font.Italic = isItalic; } /// <summary> /// 单元格字体及大小 /// </summary> /// <param name="startRow">起始行</param> /// <param name="startColumn">起始列</param> /// <param name="endRow">结束行</param> /// <param name="endColumn">结束列</param> /// <param name="fontName">字体名称</param> /// <param name="fontSize">字体大小</param> public void FontNameSize(int startRow, int startColumn, int endRow, int endColumn,string fontName, int fontSize) { Excel.Range range = myExcel.get_Range(myExcel.Cells[startRow, startColumn], myExcel.Cells[endRow, endColumn]); range.Font.Name = fontName; range.Font.Size = fontSize; } /// <summary> /// 打开一个存在的Excel文件 /// </summary> /// <param name="fileName">Excel完整路径加文件名</param> public void Open(string fileName) { myExcel = new Excel.Application(); myWorkBook = myExcel.Workbooks.Add(fileName); myFileName = fileName; } /// <summary> /// 保存Excel /// </summary> /// <returns>保存成功返回True</returns> public bool Save() { if (myFileName == "") { return false; } else { try { myWorkBook.Save(); return true; } catch (Exception ex) { return false; } } } /// <summary> /// Excel文档另存为 /// </summary> /// <param name="fileName">保存完整路径加文件名</param> /// <returns>保存成功返回True</returns> public bool SaveAs(string fileName) { try { myWorkBook.SaveAs(fileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); return true; } catch (Exception ex) { return false; } } /// <summary> /// 关闭Excel /// </summary> public void Close() { myWorkBook.Close(Type.Missing, Type.Missing, Type.Missing); myExcel.Quit(); myWorkBook = null; myExcel = null; GC.Collect(); } /// <summary> /// 关闭Excel /// </summary> /// <param name="isSave">是否保存</param> public void Close(bool isSave) { myWorkBook.Close(isSave, Type.Missing, Type.Missing); myExcel.Quit(); myWorkBook = null; myExcel = null; GC.Collect(); } /// <summary> /// 关闭Excel /// </summary> /// <param name="isSave">是否保存</param> /// <param name="fileName">存储文件名</param> public void Close(bool isSave,string fileName) { myWorkBook.Close(isSave, fileName, Type.Missing); myExcel.Quit(); myWorkBook = null; myExcel = null; GC.Collect(); } #region 私有成员 private string GetColumnName(int number) { int h, l; h = number / 26; l = number % 26; if (l == 0) { h -= 1; l = 26; } string s = GetLetter(h) + GetLetter(l); return s; } private string GetLetter(int number) { switch (number) { case 1: return "A"; case 2: return "B"; case 3: return "C"; case 4: return "D"; case 5: return "E"; case 6: return "F"; case 7: return "G"; case 8: return "H"; case 9: return "I"; case 10: return "J"; case 11: return "K"; case 12: return "L"; case 13: return "M"; case 14: return "N"; case 15: return "O"; case 16: return "P"; case 17: return "Q"; case 18: return "R"; case 19: return "S"; case 20: return "T"; case 21: return "U"; case 22: return "V"; case 23: return "W"; case 24: return "X"; case 25: return "Y"; case 26: return "Z"; default: return ""; } } #endregion } /// <summary> /// 水平对齐方式 /// </summary> public enum ExcelHAlign { 常规 = 1, 靠左, 居中, 靠右, 填充, 两端对齐, 跨列居中, 分散对齐 } /// <summary> /// 垂直对齐方式 /// </summary> public enum ExcelVAlign { 靠上 = 1, 居中, 靠下, 两端对齐, 分散对齐 } /// <summary> /// 线粗 /// </summary> public enum BorderWeight { 极细 = 1, 细 = 2, 粗 = -4138, 极粗 = 4 } /// <summary> /// 线样式 /// </summary> public enum LineStyle { 连续直线 = 1, 短线 = -4115, 线点相间 = 4, 短线间两点 = 5, 点 = -4118, 双线 = -4119, 无 = -4142, 少量倾斜点 = 13 } /// <summary> /// 下划线方式 /// </summary> public enum UnderlineStyle { 无下划线 = -4142, 双线 = - 4119, 双线充满全格 = 5, 单线 = 2, 单线充满全格 = 4 } /// <summary> /// 单元格填充方式 /// </summary> public enum Pattern { Automatic = -4105, Checker = 9, CrissCross = 16, Down = -4121, Gray16 = 17, Gray25 = -4124, Gray50 = -4125, Gray75 = -4126, Gray8 = 18, Grid = 15, Horizontal = -4128, LightDown = 13, LightHorizontal = 11, LightUp = 14, LightVertical = 12, None = -4142, SemiGray75 = 10, Solid = 1, Up = -4162, Vertical = -4166 } /// <summary> /// 常用颜色定义,对就Excel中颜色名 /// </summary> public enum ColorIndex { 无色 = -4142, 自动 = -4105, 黑色 = 1, 褐色 = 53, 橄榄 = 52, 深绿 = 51, 深青 = 49, 深蓝 = 11, 靛蓝 = 55, 灰色80 = 56, 深红 = 9, 橙色 = 46, 深黄 = 12, 绿色 = 10, 青色 = 14, 蓝色 = 5, 蓝灰 = 47, 灰色50 = 16, 红色 = 3, 浅橙色 = 45, 酸橙色 = 43, 海绿 = 50, 水绿色 = 42, 浅蓝 = 41, 紫罗兰 = 13, 灰色40 = 48, 粉红 = 7, 金色 = 44, 黄色 = 6, 鲜绿 = 4, 青绿 = 8, 天蓝 = 33, 梅红 = 54, 灰色25 = 15, 玫瑰红 = 38, 茶色 = 40, 浅黄 = 36, 浅绿 = 35, 浅青绿 = 34, 淡蓝 = 37, 淡紫 = 39, 白色 = 2 } }