關於數據庫導出到Excel和SQLServer數據導出到Excel的例子,在博客園有很多的例子,自己根據網上搜集資料,自己做了亦歌簡單的demo,現在分享出來供初學者學習交流使用。
一、數據庫導入導出到Excel,比較流行的有兩種方式:采用傳統的office類庫和采用NPOI方式。
1、傳統的office類庫 使用的時候,本地需要安裝office才可以正常使用,而且導出速度相對比較慢。有點:支持office 2003 、office2007等。
2、采用NPOI方式 本地不需要安裝office,而且導出速度比傳統的方式快的多,兩種格式一個是HSSF支持(適用2007以前的版本),另一個是XSSF(XSSF適用2007版本及其以上的)。
二、簡單代碼介紹:
1、DataTable導出到Excel的MemoryStream
1 public static MemoryStream DataGridViewToExcel(DataGridView myDgv, string strHeaderText) 2 { 3 HSSFWorkbook workbook = new HSSFWorkbook(); 4 HSSFSheet sheet = (HSSFSheet)workbook.CreateSheet(); 5 6 #region 右擊文件 屬性信息 7 { 8 DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation(); 9 dsi.Company = "NPOI"; 10 workbook.DocumentSummaryInformation = dsi; 11 12 SummaryInformation si = PropertySetFactory.CreateSummaryInformation(); 13 si.Author = "文件作者信息"; //填加xls文件作者信息 14 si.ApplicationName = "創建程序信息"; //填加xls文件創建程序信息 15 si.LastAuthor = "最后保存者信息"; //填加xls文件最后保存者信息 16 si.Comments = "作者信息"; //填加xls文件作者信息 17 si.Title = "標題信息"; //填加xls文件標題信息 18 si.Subject = "主題信息";//填加文件主題信息 19 si.CreateDateTime = System.DateTime.Now; 20 workbook.SummaryInformation = si; 21 } 22 #endregion 23 24 HSSFCellStyle dateStyle = (HSSFCellStyle)workbook.CreateCellStyle(); 25 HSSFDataFormat format = (HSSFDataFormat)workbook.CreateDataFormat(); 26 dateStyle.DataFormat = format.GetFormat("yyyy-mm-dd"); 27 28 //取得列寬 29 int[] arrColWidth = new int[myDgv.Columns.Count]; 30 foreach (DataGridViewColumn item in myDgv.Columns) 31 { 32 arrColWidth[item.Index] = Encoding.GetEncoding(936).GetBytes(item.HeaderText.ToString()).Length; 33 } 34 //可以在循環里面自己設置列寬 35 for (int i = 0; i < myDgv.Rows.Count; i++) 36 { 37 for (int j = 0; j < myDgv.Columns.Count; j++) 38 { 39 int intTemp = Encoding.GetEncoding(936).GetBytes(myDgv.Rows[i].Cells[j].ToString()).Length; 40 if (intTemp > arrColWidth[j]) 41 { 42 arrColWidth[j] = intTemp/5; 43 } 44 } 45 } 46 int rowIndex = 0; 47 foreach (DataGridViewRow row in myDgv.Rows) 48 { 49 #region 新建表,填充表頭,填充列頭,樣式 50 if (rowIndex == 65535 || rowIndex == 0) 51 { 52 if (rowIndex != 0) 53 { 54 sheet = (HSSFSheet)workbook.CreateSheet(); 55 } 56 57 #region 表頭及樣式 58 { 59 HSSFRow headerRow = (HSSFRow)sheet.CreateRow(0); 60 headerRow.HeightInPoints = 25; 61 headerRow.CreateCell(0).SetCellValue(strHeaderText); 62 63 HSSFCellStyle headStyle = (HSSFCellStyle)workbook.CreateCellStyle(); 64 // headStyle.Alignment = CellHorizontalAlignment.CENTER; 65 HSSFFont font = (HSSFFont)workbook.CreateFont(); 66 font.FontHeightInPoints = 20; 67 font.Boldweight = 700; 68 headStyle.SetFont(font); 69 headerRow.GetCell(0).CellStyle = headStyle; 70 // sheet.AddMergedRegion(new Region(0, 0, 0, dtSource.Columns.Count - 1)); 71 //headerRow.Dispose(); 72 } 73 #endregion 74 75 76 #region 列頭及樣式 77 { 78 HSSFRow headerRow = (HSSFRow)sheet.CreateRow(1); 79 HSSFCellStyle headStyle = (HSSFCellStyle)workbook.CreateCellStyle(); 80 //headStyle.Alignment = CellHorizontalAlignment.CENTER; 81 HSSFFont font = (HSSFFont)workbook.CreateFont(); 82 font.FontHeightInPoints = 10; 83 font.Boldweight = 700; 84 headStyle.SetFont(font); 85 foreach (DataGridViewColumn column in myDgv.Columns) 86 { 87 headerRow.CreateCell(column.Index).SetCellValue(column.HeaderText); 88 headerRow.GetCell(column.Index).CellStyle = headStyle; 89 90 //設置列寬 91 sheet.SetColumnWidth(column.Index, (arrColWidth[column.Index] + 1) * 256); 92 } 93 // headerRow.Dispose(); 94 } 95 #endregion 96 97 rowIndex = 2; 98 } 99 #endregion 100 101 102 #region 填充內容 103 HSSFRow dataRow = (HSSFRow)sheet.CreateRow(rowIndex); 104 if (row.Index > 0) 105 { 106 foreach (DataGridViewColumn column in myDgv.Columns) 107 { 108 HSSFCell newCell = (HSSFCell)dataRow.CreateCell(column.Index); 109 110 string drValue = myDgv[column.Index, row.Index-1].Value.ToString(); 111 112 switch (column.ValueType.ToString()) 113 { 114 case "System.String"://字符串類型 115 newCell.SetCellValue(drValue); 116 break; 117 case "System.DateTime"://日期類型 118 System.DateTime dateV; 119 System.DateTime.TryParse(drValue, out dateV); 120 newCell.SetCellValue(dateV); 121 122 newCell.CellStyle = dateStyle;//格式化顯示 123 break; 124 case "System.Boolean"://布爾型 125 bool boolV = false; 126 bool.TryParse(drValue, out boolV); 127 newCell.SetCellValue(boolV); 128 break; 129 case "System.Int16"://整型 130 case "System.Int32": 131 case "System.Int64": 132 case "System.Byte": 133 int intV = 0; 134 int.TryParse(drValue, out intV); 135 newCell.SetCellValue(intV); 136 break; 137 case "System.Decimal"://浮點型 138 case "System.Double": 139 double doubV = 0; 140 double.TryParse(drValue, out doubV); 141 newCell.SetCellValue(doubV); 142 break; 143 case "System.DBNull"://空值處理 144 newCell.SetCellValue(""); 145 break; 146 default: 147 newCell.SetCellValue(""); 148 break; 149 } 150 151 } 152 } 153 else 154 { rowIndex--; } 155 #endregion 156 157 rowIndex++; 158 } 159 using (MemoryStream ms = new MemoryStream()) 160 { 161 workbook.Write(ms); 162 ms.Flush(); 163 ms.Position = 0; 164 165 sheet.Dispose(); 166 //workbook.Dispose();//一般只用寫這一個就OK了,他會遍歷並釋放所有資源,但當前版本有問題所以只釋放sheet 167 return ms; 168 } 169 }
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 + "");
}
說明:本人屬於新手寫文章,水平有限,如果發現文章有錯誤的地方,歡迎指出,多謝各位朋友,希望大家共同進步
