關於數據庫導出到Excel和SQLServer數據導出到Excel的例子,在博客園有很多的例子,自己根據網上搜集資料,自己做了亦歌簡單的demo,現在分享出來供初學者學習交流使用。
一、數據庫導入導出到Excel,比較流行的有兩種方式:采用傳統的office類庫和采用NPOI方式。
1、傳統的office類庫 使用的時候,本地需要安裝office才可以正常使用,而且導出速度相對比較慢。有點:支持office 2003 、office2007等。
2、采用NPOI方式 本地不需要安裝office,而且導出速度比傳統的方式快的多,缺點是:主要支持office2003 帶的excel操作比較局限。
二、簡單代碼介紹:
1、DataTable導出到Excel的MemoryStream
public static MemoryStream DataGridViewToExcel(DataGridView myDgv, string strHeaderText) { HSSFWorkbook workbook = new HSSFWorkbook(); HSSFSheet sheet = (HSSFSheet)workbook.CreateSheet(); #region 右擊文件 屬性信息 { DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation(); dsi.Company = "NPOI"; workbook.DocumentSummaryInformation = dsi; SummaryInformation si = PropertySetFactory.CreateSummaryInformation(); si.Author = "文件作者信息"; //填加xls文件作者信息 si.ApplicationName = "創建程序信息"; //填加xls文件創建程序信息 si.LastAuthor = "最後保存者信息"; //填加xls文件最後保存者信息 si.Comments = "作者信息"; //填加xls文件作者信息 si.Title = "標題信息"; //填加xls文件標題信息 si.Subject = "主題信息";//填加文件主題信息 si.CreateDateTime = System.DateTime.Now; workbook.SummaryInformation = si; } #endregion HSSFCellStyle dateStyle = (HSSFCellStyle)workbook.CreateCellStyle(); HSSFDataFormat format = (HSSFDataFormat)workbook.CreateDataFormat(); dateStyle.DataFormat = format.GetFormat("yyyy-mm-dd"); //取得列寬 int[] arrColWidth = new int[myDgv.Columns.Count]; foreach (DataGridViewColumn item in myDgv.Columns) { arrColWidth[item.Index] = Encoding.GetEncoding(936).GetBytes(item.HeaderText.ToString()).Length; } //可以在循環裡面自己設置列寬 for (int i = 0; i < myDgv.Rows.Count; i++) { for (int j = 0; j < myDgv.Columns.Count; j++) { int intTemp = Encoding.GetEncoding(936).GetBytes(myDgv.Rows[i].Cells[j].ToString()).Length; if (intTemp > arrColWidth[j]) { arrColWidth[j] = intTemp/5; } } } int rowIndex = 0; foreach (DataGridViewRow row in myDgv.Rows) { #region 新建表,填充表頭,填充列頭,樣式 if (rowIndex == 65535 || rowIndex == 0) { if (rowIndex != 0) { sheet = (HSSFSheet)workbook.CreateSheet(); } #region 表頭及樣式 { HSSFRow headerRow = (HSSFRow)sheet.CreateRow(0); headerRow.HeightInPoints = 25; headerRow.CreateCell(0).SetCellValue(strHeaderText); HSSFCellStyle headStyle = (HSSFCellStyle)workbook.CreateCellStyle(); // headStyle.Alignment = CellHorizontalAlignment.CENTER; HSSFFont font = (HSSFFont)workbook.CreateFont(); font.FontHeightInPoints = 20; font.Boldweight = 700; headStyle.SetFont(font); headerRow.GetCell(0).CellStyle = headStyle; // sheet.AddMergedRegion(new Region(0, 0, 0, dtSource.Columns.Count - 1)); //headerRow.Dispose(); } #endregion #region 列頭及樣式 { HSSFRow headerRow = (HSSFRow)sheet.CreateRow(1); HSSFCellStyle headStyle = (HSSFCellStyle)workbook.CreateCellStyle(); //headStyle.Alignment = CellHorizontalAlignment.CENTER; HSSFFont font = (HSSFFont)workbook.CreateFont(); font.FontHeightInPoints = 10; font.Boldweight = 700; headStyle.SetFont(font); foreach (DataGridViewColumn column in myDgv.Columns) { headerRow.CreateCell(column.Index).SetCellValue(column.HeaderText); headerRow.GetCell(column.Index).CellStyle = headStyle; //設置列寬 sheet.SetColumnWidth(column.Index, (arrColWidth[column.Index] + 1) * 256); } // headerRow.Dispose(); } #endregion rowIndex = 2; } #endregion #region 填充內容 HSSFRow dataRow = (HSSFRow)sheet.CreateRow(rowIndex); if (row.Index > 0) { foreach (DataGridViewColumn column in myDgv.Columns) { HSSFCell newCell = (HSSFCell)dataRow.CreateCell(column.Index); string drValue = myDgv[column.Index, row.Index-1].Value.ToString(); switch (column.ValueType.ToString()) { case "System.String"://字符串類型 newCell.SetCellValue(drValue); break; case "System.DateTime"://日期類型 System.DateTime dateV; System.DateTime.TryParse(drValue, out dateV); newCell.SetCellValue(dateV); newCell.CellStyle = dateStyle;//格式化顯示 break; case "System.Boolean"://布爾型 bool boolV = false; bool.TryParse(drValue, out boolV); newCell.SetCellValue(boolV); break; case "System.Int16"://整型 case "System.Int32": case "System.Int64": case "System.Byte": int intV = 0; int.TryParse(drValue, out intV); newCell.SetCellValue(intV); break; case "System.Decimal"://浮點型 case "System.Double": double doubV = 0; double.TryParse(drValue, out doubV); newCell.SetCellValue(doubV); break; case "System.DBNull"://空值處理 newCell.SetCellValue(""); break; default: newCell.SetCellValue(""); break; } } } else { rowIndex--; } #endregion rowIndex++; } using (MemoryStream ms = new MemoryStream()) { workbook.Write(ms); ms.Flush(); ms.Position = 0; sheet.Dispose(); //workbook.Dispose();//一般只用寫這一個就OK了,他會遍歷並釋放所有資源,但當前版本有問題所以只釋放sheet return ms; } }
2、讀取excel到DataTable
/// <summary>讀取excel /// 默認第一行為標頭 /// </summary> /// <param name="strFileName">excel文檔路徑</param> /// <returns></returns> public static DataTable Import(string strFileName) { DataTable dt = new DataTable(); HSSFWorkbook hssfworkbook; using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read)) { hssfworkbook = new HSSFWorkbook(file); } HSSFSheet sheet = (HSSFSheet)hssfworkbook.GetSheetAt(0); System.Collections.IEnumerator rows = sheet.GetRowEnumerator(); HSSFRow headerRow = (HSSFRow)sheet.GetRow(0); int cellCount = headerRow.LastCellNum; //獲取表頭 for (int j = 0; j < cellCount; j++) { HSSFCell cell = (HSSFCell)headerRow.GetCell(j); dt.Columns.Add(cell.ToString()); } for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++) { HSSFRow row = (HSSFRow)sheet.GetRow(i); DataRow dataRow = dt.NewRow(); for (int j = row.FirstCellNum; j < cellCount; j++) { if (row.GetCell(j) != null) dataRow[j] = row.GetCell(j).ToString(); } dt.Rows.Add(dataRow); } return dt; }
3、批量導入大批量數據的寫法( SqlBulkCopy )
private void btnImport_Click(object sender, EventArgs e) { string constr = System.Configuration.ConfigurationSettings.AppSettings["connstr"].ToString(); #region 選擇文件模塊 string path = ""; //初始化一個OpenFileDialog類 OpenFileDialog fileDialog = new OpenFileDialog(); //判斷用戶是否正確的選擇了文件 if (fileDialog.ShowDialog() == DialogResult.OK) { //獲取用戶選擇文件的後綴名 string extension = Path.GetExtension(fileDialog.FileName); //聲明允許的後綴名 string[] str = new string[] { ".xls" }; if (!((IList)str).Contains(extension)) { MessageBox.Show("僅能上傳xls格式的Excel文件!"); } else { //獲取用戶選擇的文件,並判斷文件大小不能超過20K,fileInfo.Length是以字節為單位的 FileInfo fileInfo = new FileInfo(fileDialog.FileName); if (fileInfo.Length > 204800000) { MessageBox.Show("上傳的Excel不能大於200M"); } else { path = fileDialog.FileName; //在這裡就可以寫獲取到正確文件後的代碼了 } } } #endregion System.Diagnostics.Stopwatch timeWatch = System.Diagnostics.Stopwatch.StartNew(); DataTable dtnew = NPOIExcelHelper.Import(path); DataTable ss = GetDt(); if (dt != null && dt.Rows.Count != 0) { int n = 2500; //遍歷每一行執行插入操作 foreach (DataRow item in dtnew.Rows) { ss.Rows.Add(n,2, item["專業名稱"], item["專業代碼"], DateTime.Now, 0); n++; } } SqlBulkCopy sqlbulkcopy = new SqlBulkCopy(constr, SqlBulkCopyOptions.UseInternalTransaction); sqlbulkcopy.DestinationTableName = "COMM_ZZ_COURSE_CLASS";//數據庫中的表名 sqlbulkcopy.WriteToServer(ss); timeWatch.Stop(); MessageBox.Show("數據導入成功耗時為:" + timeWatch.Elapsed + ""); }
說明:本人屬於新手寫文章,水平有限,如果發現文章有錯誤的地方,歡迎指出,多謝各位朋友,希望大家共同進步
代碼下載 http://pan.baidu.com/s/1jIB8LoE