c#_导出table功能
生活随笔
收集整理的這篇文章主要介紹了
c#_导出table功能
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
一:第一張導出方法,簡單快捷 請注意:一般表格都有真分頁,查詢數據時候注意把分頁條件去掉
#region 此處是獲取的list數組 然后轉table再調用ExportExcel
var list="你的list數據庫源"DataTable dt = new DataTable();dt.Columns.Add("序號", typeof(string));dt.Columns.Add("姓名", typeof(string));int datacount = 1;foreach (var item in list)//list給table賦值 { DataRow tr = dt.NewRow(); tr[0] = datacount; tr[1] = item.XM; datacount++; }
//然后調用 ExportExcel("dt","文件名字")
//或者直接調用 ExportExcel("table數據源","文件名字")
/// <summary>/// 導出功能 此方法直接給table 和導出的文件名即可 已經封裝好 直接調用/// </summary>/// <param name="dt">數據源</param>/// <param name="tablename">導出的名字</param>public void ExportExcel(DataTable dt, string filename){string path = AppDomain.CurrentDomain.BaseDirectory + @"" + filename + ".xls";WriteExcel(dt, path);System.IO.FileInfo filet = new System.IO.FileInfo(path);Response.Clear();Response.Charset = "GB2312";Response.ContentEncoding = System.Text.Encoding.UTF8;Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(filename + ".xls"));Response.AddHeader("Content-Length", filet.Length.ToString());Response.ContentType = "application/ms-excel";Response.WriteFile(filet.FullName);Response.End();}public void WriteExcel(DataTable dt, string path){try{long totalCount = dt.Rows.Count;long rowRead = 0;float percent = 0;System.IO.StreamWriter sw = new System.IO.StreamWriter(path, false, System.Text.Encoding.GetEncoding("gb2312"));System.Text.StringBuilder sb = new System.Text.StringBuilder();for (int k = 0; k < dt.Columns.Count; k++){sb.Append(dt.Columns[k].ColumnName.ToString() + " \t");}sb.Append(Environment.NewLine);for (int i = 0; i < dt.Rows.Count; i++){rowRead++;percent = ((float)(100 * rowRead)) / totalCount;for (int j = 0; j < dt.Columns.Count; j++){sb.Append(dt.Rows[i][j].ToString() + "\t");}sb.Append(Environment.NewLine);}sw.Write(sb.ToString());sw.Flush();sw.Close();}catch (Exception ex){}}
此導出方式實際是.CSV(數字與純文本格式)能用excel打開而已? 所以在設置導出格式無能為力(如時間格式就會出現問題)
#region 此處是獲取的list數組 然后轉table再調用ExportExcel
var list="你的list數據庫源"DataTable dt = new DataTable();dt.Columns.Add("序號", typeof(string));dt.Columns.Add("姓名", typeof(string));int datacount = 1;foreach (var item in list)//list給table賦值 { DataRow tr = dt.NewRow(); tr[0] = datacount; tr[1] = item.XM; datacount++; }
//然后調用 ExportExcel("dt","文件名字")
//或者直接調用 ExportExcel("table數據源","文件名字")
/// <summary>/// 導出功能 此方法直接給table 和導出的文件名即可 已經封裝好 直接調用/// </summary>/// <param name="dt">數據源</param>/// <param name="tablename">導出的名字</param>public void ExportExcel(DataTable dt, string filename){string path = AppDomain.CurrentDomain.BaseDirectory + @"" + filename + ".xls";WriteExcel(dt, path);System.IO.FileInfo filet = new System.IO.FileInfo(path);Response.Clear();Response.Charset = "GB2312";Response.ContentEncoding = System.Text.Encoding.UTF8;Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(filename + ".xls"));Response.AddHeader("Content-Length", filet.Length.ToString());Response.ContentType = "application/ms-excel";Response.WriteFile(filet.FullName);Response.End();}public void WriteExcel(DataTable dt, string path){try{long totalCount = dt.Rows.Count;long rowRead = 0;float percent = 0;System.IO.StreamWriter sw = new System.IO.StreamWriter(path, false, System.Text.Encoding.GetEncoding("gb2312"));System.Text.StringBuilder sb = new System.Text.StringBuilder();for (int k = 0; k < dt.Columns.Count; k++){sb.Append(dt.Columns[k].ColumnName.ToString() + " \t");}sb.Append(Environment.NewLine);for (int i = 0; i < dt.Rows.Count; i++){rowRead++;percent = ((float)(100 * rowRead)) / totalCount;for (int j = 0; j < dt.Columns.Count; j++){sb.Append(dt.Rows[i][j].ToString() + "\t");}sb.Append(Environment.NewLine);}sw.Write(sb.ToString());sw.Flush();sw.Close();}catch (Exception ex){}}
此導出方式實際是.CSV(數字與純文本格式)能用excel打開而已? 所以在設置導出格式無能為力(如時間格式就會出現問題)
?
?
二:第二種,能改變導出excel格式
? 引用 NPOI文件來進行 導出,? 也是封裝好的, 只需要把相對應的引用文件? 引用好直接調用就可以
引用到的NPOI?
?請注意: 此方法無法用于AJAX ,可解決導出時間或者身份證顯示######問題
?例子
?
//前臺調用導出按鈕$("#WriteDoctor").click(function () {var StartTime = $("#startDate").val();var EndTime = $("#endDate").val();var Department = $(".drop_btn .drop_btn_val").text();var DoctorName = $(".drop_btn2 .drop_btn_val").text();if (Department == "全部") {Department = ""}if (DoctorName == "全部") {DoctorName = ""}window.location.href = "@Url.Action("WriteDoctor")?StartTime=" + StartTime + "&EndTime=" + EndTime ;})//后臺方法public ActionResult WriteDoctor(DateTime StartTime){DataSet ds = 去查詢數據庫數據(DateTIme, StarTime);string paths = "table表名字" + DateTime.Now.ToString("yyyyMMdd") + ".xls"; NPOIHelper.ExportByWeb(ds, "table表名字" + DateTime.Now.ToString("yyyyMMdd"), paths);return Json(new { success = true }, JsonRequestBehavior.AllowGet);}?
?
using NPOI.HPSF; using NPOI.HSSF.UserModel; using NPOI.SS.UserModel; using NPOI.SS.Util; using NPOI.XSSF.UserModel; using System; using System.Collections.Generic; using System.Data; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Web; //引用 System.Web using System.Collections.Generic;namespace DBUtility {public class NPOIHelper{/// <summary>/// DataTable導出到Excel文件/// </summary>/// <param name="dtSource">源DataTable</param>/// <param name="strHeaderText">表頭文本</param>/// <param name="strFileName">保存位置</param>public static void Export(DataTable dtSource, string strHeaderText, string strFileName){using (MemoryStream ms = Export(dtSource, strHeaderText)){using (FileStream fs = new FileStream(strFileName, FileMode.Create, FileAccess.Write)){byte[] data = ms.ToArray();fs.Write(data, 0, data.Length);fs.Flush();}}}/// <summary>/// DataTable導出到Excel的MemoryStream/// </summary>/// <param name="dtSource">源DataTable</param>/// <param name="strHeaderText">表頭文本</param>public static MemoryStream Export(DataTable dtSource, string strHeaderText){HSSFWorkbook workbook = new HSSFWorkbook();ISheet sheet = workbook.CreateSheet();#region 右擊文件 屬性信息{DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();dsi.Company = "";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 = DateTime.Now;workbook.SummaryInformation = si;}#endregionICellStyle dateStyle = workbook.CreateCellStyle();IDataFormat format = workbook.CreateDataFormat();ICellStyle dataStyle = workbook.CreateCellStyle();dateStyle.DataFormat = format.GetFormat("yyyy-mm-dd");dateStyle.Alignment = HorizontalAlignment.Center;dateStyle.VerticalAlignment = VerticalAlignment.Center;dateStyle.BorderBottom = BorderStyle.Thin;dateStyle.BorderLeft = BorderStyle.Thin;dateStyle.BorderRight = BorderStyle.Thin;dateStyle.BorderTop = BorderStyle.Thin;//-----dataStyle.Alignment = HorizontalAlignment.Center;dataStyle.VerticalAlignment = VerticalAlignment.Center;dataStyle.BorderBottom = BorderStyle.Thin;dataStyle.BorderLeft = BorderStyle.Thin;dataStyle.BorderRight = BorderStyle.Thin;dataStyle.BorderTop = BorderStyle.Thin;//取得列寬int[] arrColWidth = new int[dtSource.Columns.Count];foreach (DataColumn item in dtSource.Columns){arrColWidth[item.Ordinal] = Encoding.GetEncoding(936).GetBytes(item.ColumnName.ToString()).Length;}for (int i = 0; i < dtSource.Rows.Count; i++){for (int j = 0; j < dtSource.Columns.Count; j++){int intTemp = Encoding.GetEncoding(936).GetBytes(dtSource.Rows[i][j].ToString()).Length;if (intTemp > arrColWidth[j]){arrColWidth[j] = intTemp;}}}int rowIndex = 0;foreach (DataRow row in dtSource.Rows){#region 新建表,填充表頭,填充列頭,樣式if (rowIndex == 65535 || rowIndex == 0){if (rowIndex != 0){sheet = workbook.CreateSheet();}#region 表頭及樣式{IRow headerRow = sheet.CreateRow(0);headerRow.HeightInPoints = 25;headerRow.CreateCell(0).SetCellValue(strHeaderText);ICellStyle headStyle = workbook.CreateCellStyle();headStyle.Alignment = HorizontalAlignment.Center;headStyle.VerticalAlignment = VerticalAlignment.Center;IFont font = workbook.CreateFont();font.FontHeightInPoints = 12;font.Boldweight = 600;headStyle.SetFont(font);headerRow.GetCell(0).CellStyle = headStyle;sheet.AddMergedRegion(new CellRangeAddress(0, 0, 0, dtSource.Columns.Count - 1));}#endregion#region 列頭及樣式{IRow headerRow = sheet.CreateRow(1);ICellStyle headStyle = workbook.CreateCellStyle();headStyle.Alignment = HorizontalAlignment.Center;headStyle.VerticalAlignment = VerticalAlignment.Center;headStyle.BorderBottom = BorderStyle.Thin;headStyle.BorderLeft = BorderStyle.Thin;headStyle.BorderRight = BorderStyle.Thin;headStyle.BorderTop = BorderStyle.Thin;IFont font = workbook.CreateFont();font.FontHeightInPoints = 10;font.Boldweight = 600;headStyle.SetFont(font);foreach (DataColumn column in dtSource.Columns){headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);headerRow.GetCell(column.Ordinal).CellStyle = headStyle;//設置列寬sheet.SetColumnWidth(column.Ordinal, (arrColWidth[column.Ordinal] + 1) * 256);}// headerRow.Dispose(); }#endregionrowIndex = 2;}#endregion#region 填充內容IRow dataRow = sheet.CreateRow(rowIndex);foreach (DataColumn column in dtSource.Columns){ICell newCell = dataRow.CreateCell(column.Ordinal);string drValue = row[column].ToString();switch (column.DataType.ToString()){case "System.String"://字符串類型 newCell.SetCellValue(drValue);newCell.CellStyle = dataStyle;break;case "System.DateTime"://日期類型 DateTime dateV;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);newCell.CellStyle = dataStyle;break;case "System.Int16"://整型case "System.Int32":case "System.Int64":case "System.Byte":int intV = 0;int.TryParse(drValue, out intV);newCell.SetCellValue(intV);newCell.CellStyle = dataStyle;break;case "System.Decimal"://浮點型case "System.Double":double doubV = 0;double.TryParse(drValue, out doubV);newCell.SetCellValue(doubV);newCell.CellStyle = dataStyle;break;case "System.DBNull"://空值處理newCell.SetCellValue("");newCell.CellStyle = dataStyle;break;default:newCell.SetCellValue("");newCell.CellStyle = dataStyle;break;}}#endregionrowIndex++;}using (MemoryStream ms = new MemoryStream()){workbook.Write(ms);ms.Flush();ms.Position = 0;////workbook.c// workbook//workbook.Dispose();//一般只用寫這一個就OK了,他會遍歷并釋放所有資源,但當前版本有問題所以只釋放sheetreturn ms;}}/// <summary>/// DataTable導出到Excel的MemoryStream/// </summary>/// <param name="dtSource">源DataSet</param>/// <param name="strHeaderText">表頭文本</param>public static MemoryStream ExportMoreTable(DataSet dsSource, string strHeaderText){HSSFWorkbook workbook = new HSSFWorkbook();foreach (DataTable dtSource in dsSource.Tables){ISheet sheet = workbook.CreateSheet();#region 右擊文件 屬性信息{DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();dsi.Company = "";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 = DateTime.Now;workbook.SummaryInformation = si;}#endregionICellStyle dateStyle = workbook.CreateCellStyle();IDataFormat format = workbook.CreateDataFormat();ICellStyle dataStyle = workbook.CreateCellStyle();dateStyle.DataFormat = format.GetFormat("yyyy-mm-dd");dateStyle.Alignment = HorizontalAlignment.Center;dateStyle.VerticalAlignment = VerticalAlignment.Center;dateStyle.BorderBottom = BorderStyle.Thin;dateStyle.BorderLeft = BorderStyle.Thin;dateStyle.BorderRight = BorderStyle.Thin;dateStyle.BorderTop = BorderStyle.Thin;//-----dataStyle.Alignment = HorizontalAlignment.Center;dataStyle.VerticalAlignment = VerticalAlignment.Center;dataStyle.BorderBottom = BorderStyle.Thin;dataStyle.BorderLeft = BorderStyle.Thin;dataStyle.BorderRight = BorderStyle.Thin;dataStyle.BorderTop = BorderStyle.Thin;//取得列寬int[] arrColWidth = new int[dtSource.Columns.Count];foreach (DataColumn item in dtSource.Columns){arrColWidth[item.Ordinal] = Encoding.GetEncoding(936).GetBytes(item.ColumnName.ToString()).Length;}for (int i = 0; i < dtSource.Rows.Count; i++){for (int j = 0; j < dtSource.Columns.Count; j++){int intTemp = Encoding.GetEncoding(936).GetBytes(dtSource.Rows[i][j].ToString()).Length;if (intTemp > arrColWidth[j]){arrColWidth[j] = intTemp;}}}int rowIndex = 0;foreach (DataRow row in dtSource.Rows){#region 新建表,填充表頭,填充列頭,樣式if (rowIndex == 65535 || rowIndex == 0){if (rowIndex != 0){sheet = workbook.CreateSheet();}#region 表頭及樣式{IRow headerRow = sheet.CreateRow(0);headerRow.HeightInPoints = 25;headerRow.CreateCell(0).SetCellValue(strHeaderText);ICellStyle headStyle = workbook.CreateCellStyle();headStyle.Alignment = HorizontalAlignment.Center;headStyle.VerticalAlignment = VerticalAlignment.Center;IFont font = workbook.CreateFont();font.FontHeightInPoints = 12;font.Boldweight = 600;headStyle.SetFont(font);headerRow.GetCell(0).CellStyle = headStyle;sheet.AddMergedRegion(new CellRangeAddress(0, 0, 0, dtSource.Columns.Count - 1));}#endregion#region 列頭及樣式{IRow headerRow = sheet.CreateRow(1);ICellStyle headStyle = workbook.CreateCellStyle();headStyle.Alignment = HorizontalAlignment.Center;headStyle.VerticalAlignment = VerticalAlignment.Center;headStyle.BorderBottom = BorderStyle.Thin;headStyle.BorderLeft = BorderStyle.Thin;headStyle.BorderRight = BorderStyle.Thin;headStyle.BorderTop = BorderStyle.Thin;IFont font = workbook.CreateFont();font.FontHeightInPoints = 10;font.Boldweight = 600;headStyle.SetFont(font);foreach (DataColumn column in dtSource.Columns){headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);headerRow.GetCell(column.Ordinal).CellStyle = headStyle;//設置列寬sheet.SetColumnWidth(column.Ordinal, (arrColWidth[column.Ordinal] + 1) * 256);}// headerRow.Dispose(); }#endregionrowIndex = 2;}#endregion#region 填充內容IRow dataRow = sheet.CreateRow(rowIndex);foreach (DataColumn column in dtSource.Columns){ICell newCell = dataRow.CreateCell(column.Ordinal);string drValue = row[column].ToString();switch (column.DataType.ToString()){case "System.String"://字符串類型 newCell.SetCellValue(drValue);newCell.CellStyle = dataStyle;break;case "System.DateTime"://日期類型 DateTime dateV;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);newCell.CellStyle = dataStyle;break;case "System.Int16"://整型case "System.Int32":case "System.Int64":case "System.Byte":int intV = 0;int.TryParse(drValue, out intV);newCell.SetCellValue(intV);newCell.CellStyle = dataStyle;break;case "System.Decimal"://浮點型case "System.Double":double doubV = 0;double.TryParse(drValue, out doubV);newCell.SetCellValue(doubV);newCell.CellStyle = dataStyle;break;case "System.DBNull"://空值處理newCell.SetCellValue("");newCell.CellStyle = dataStyle;break;default:newCell.SetCellValue("");newCell.CellStyle = dataStyle;break;}}#endregionrowIndex++;}}using (MemoryStream ms = new MemoryStream()){workbook.Write(ms);ms.Flush();ms.Position = 0;////workbook.c// workbook//workbook.Dispose();//一般只用寫這一個就OK了,他會遍歷并釋放所有資源,但當前版本有問題所以只釋放sheetreturn ms;}}///// <summary>///// 用于Web網頁 直接導出///// </summary>///// <param name="dtSource">源DataTable</param>///// <param name="strHeaderText">表頭文本</param>///// <param name="strFileName">文件名</param>public static void ExportByWeb(DataSet dtSource, string strHeaderText, string strFileName){HttpContext curContext = HttpContext.Current;// 設置編碼和附件格式curContext.Response.ContentType = "application/vnd.ms-excel";curContext.Response.ContentEncoding = Encoding.UTF8;curContext.Response.Charset = "";curContext.Response.AppendHeader("Content-Disposition","attachment;filename=" + HttpUtility.UrlEncode(strFileName, Encoding.UTF8));curContext.Response.BinaryWrite(ExportMoreTable(dtSource, strHeaderText).GetBuffer());curContext.Response.End();}public static void ExportByWeb(MemoryStream file, string strFileName){HttpContext curContext = HttpContext.Current;// 設置編碼和附件格式curContext.Response.ContentType = "application/vnd.ms-excel";curContext.Response.ContentEncoding = Encoding.UTF8;curContext.Response.Charset = "";curContext.Response.AppendHeader("Content-Disposition","attachment;filename=" + HttpUtility.UrlEncode(strFileName, Encoding.UTF8));curContext.Response.BinaryWrite(file.ToArray());curContext.Response.End();}/// <summary>讀取excel/// 默認第一行為標頭/// </summary>/// <param name="strFileName">excel文檔路徑</param>/// <returns></returns>public static DataTable Import(string strFileName){DataTable dt = new DataTable();//XSSFWorkbook xhssfworkbook; HSSFWorkbook hssfworkbook;using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read)){hssfworkbook = new HSSFWorkbook(file);}ISheet sheet = hssfworkbook.GetSheetAt(0);System.Collections.IEnumerator rows = sheet.GetRowEnumerator();IRow headerRow = sheet.GetRow(0);int cellCount = headerRow.LastCellNum;for (int j = 0; j < cellCount; j++){ICell cell = headerRow.GetCell(j);dt.Columns.Add(cell.ToString());}for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++){IRow row = 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;}public static DataTable ImportOther(string strFileName){DataTable dt = new DataTable();HSSFWorkbook hssfworkbook;XSSFWorkbook xhssfworkbook;ISheet sheet = null;using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read)){if (!strFileName.Contains(".xlsx")){hssfworkbook = new HSSFWorkbook(file);sheet = hssfworkbook.GetSheetAt(0);}else{xhssfworkbook = new XSSFWorkbook(file);sheet = xhssfworkbook.GetSheetAt(0);}}System.Collections.IEnumerator rows = sheet.GetRowEnumerator();IRow headerRow = sheet.GetRow(0);int cellCount = headerRow.LastCellNum;for (int j = 0; j < cellCount; j++){ICell cell = headerRow.GetCell(j);dt.Columns.Add(cell.ToString());}for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++){IRow row = 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;}/// <summary>/// 將datatable導出為excel/// 圖片默認顯示在excel 第二行最后一列/// </summary>/// <param name="table">數據源</param>/// <param name="excelInfo">Tuple<excel列名,datatable列名,excel列寬度></param>/// <param name="sheetName">工作簿名稱</param>/// <param name="picBytes">導出圖片字節流</param>/// <param name="mergedRegion">合并單元格信息:null不合并單元格</param>/// <returns></returns>public static MemoryStream ExportToExcel2007(DataTable table, List<Tuple<string, string, int>> excelInfo, string sheetName, byte[] picBytes, List<CellRangeAddress> mergedRegion){MemoryStream ms = new MemoryStream();try{using (table){IWorkbook workbook = new XSSFWorkbook();ISheet sheet = workbook.CreateSheet(sheetName);for (int i = 0; i < excelInfo.Count; i++){sheet.SetColumnWidth(i, excelInfo[i].Item3 * 256);}IRow headerRow = sheet.CreateRow(0);for (int i = 0; i < excelInfo.Count; i++){headerRow.CreateCell(i).SetCellValue(excelInfo[i].Item1);}int rowIndex = 1;foreach (DataRow row in table.Rows){IRow dataRow = sheet.CreateRow(rowIndex);for (int i = 0; i < excelInfo.Count; i++){dataRow.CreateCell(i).SetCellValue(row[excelInfo[i].Item2].ToString());}rowIndex++;}//合并單元格if (mergedRegion != null && mergedRegion.Count > 0){foreach (CellRangeAddress cellRangeAddress in mergedRegion){//設置一個合并單元格區域,使用上下左右定義CellRangeAddress區域//CellRangeAddress四個參數為:起始行,結束行,起始列,結束列 sheet.AddMergedRegion(cellRangeAddress);ICellStyle style = workbook.CreateCellStyle();//設置單元格的樣式:水平對齊居中style.Alignment = HorizontalAlignment.Center;//將新的樣式賦給單元格var cell = sheet.GetRow(cellRangeAddress.FirstRow).GetCell(cellRangeAddress.FirstColumn);cell.CellStyle = style;}}//插入圖片if (picBytes != null && picBytes.Length > 0){var row1 = 2;var col1 = excelInfo.Count + 1;/* Add Picture to Workbook, Specify picture type as PNG and Get an Index */int pictureIdx = workbook.AddPicture(picBytes, NPOI.SS.UserModel.PictureType.PNG); //添加圖片/* Create the drawing container */XSSFDrawing drawing = (XSSFDrawing)sheet.CreateDrawingPatriarch();/* Create an anchor point */XSSFClientAnchor anchor = new XSSFClientAnchor(0, 0, 0, 240, col1, row1, col1 + 1, row1 + 1);/* Invoke createPicture and pass the anchor point and ID */XSSFPicture picture = (XSSFPicture)drawing.CreatePicture(anchor, pictureIdx);/* Call resize method, which resizes the image */picture.Resize();picBytes = null;}workbook.Write(ms);// workbook.Close(); }}catch (Exception ex){ms = null;}return ms;}/// <summary>/// 將datatable導出為excel/// 圖片默認顯示在excel 第二行最后一列/// </summary>/// <param name="table">數據源</param>/// <param name="excelInfo">Tuple<excel列名,datatable列名,excel列寬度></param>/// <param name="sheetName">工作簿名稱</param>/// <param name="picBytes">導出圖片字節流</param>/// <param name="mergedRegion">合并單元格信息:null不合并單元格</param>/// <returns></returns>public static MemoryStream ExportToExcel97(DataTable table, List<Tuple<string, string, int>> excelInfo, string sheetName, byte[] picBytes, List<CellRangeAddress> mergedRegion){MemoryStream ms = new MemoryStream();try{using (table){IWorkbook workbook = new HSSFWorkbook();ISheet sheet = workbook.CreateSheet(sheetName);for (int i = 0; i < excelInfo.Count; i++){sheet.SetColumnWidth(i, excelInfo[i].Item3 * 256);}IRow headerRow = sheet.CreateRow(0);for (int i = 0; i < excelInfo.Count; i++){headerRow.CreateCell(i).SetCellValue(excelInfo[i].Item1);}int rowIndex = 1;foreach (DataRow row in table.Rows){IRow dataRow = sheet.CreateRow(rowIndex);for (int i = 0; i < excelInfo.Count; i++){dataRow.CreateCell(i).SetCellValue(row[excelInfo[i].Item2].ToString());}rowIndex++;}//合并單元格if (mergedRegion != null && mergedRegion.Count > 0){foreach (CellRangeAddress cellRangeAddress in mergedRegion){//設置一個合并單元格區域,使用上下左右定義CellRangeAddress區域//CellRangeAddress四個參數為:起始行,結束行,起始列,結束列 sheet.AddMergedRegion(cellRangeAddress);ICellStyle style = workbook.CreateCellStyle();//設置單元格的樣式:水平對齊居中style.Alignment = HorizontalAlignment.Center;//將新的樣式賦給單元格var cell = sheet.GetRow(cellRangeAddress.FirstRow).GetCell(cellRangeAddress.FirstColumn);cell.CellStyle = style;}}//插入圖片if (picBytes != null && picBytes.Length > 0){var row1 = 2;var col1 = excelInfo.Count + 1;int pictureIdx = workbook.AddPicture(picBytes, NPOI.SS.UserModel.PictureType.PNG); //添加圖片 HSSFPatriarch patriarch = (HSSFPatriarch)sheet.CreateDrawingPatriarch();HSSFClientAnchor anchor = new HSSFClientAnchor(0, 0, 0, 240, col1, row1, col1 + 1, row1 + 1);//圖片位置,圖片左上角為(col, row)HSSFPicture pict = (HSSFPicture)patriarch.CreatePicture(anchor, pictureIdx);pict.Resize(); //用圖片原始大小來顯示picBytes = null;}workbook.Write(ms);ms.Flush();ms.Position = 0;}}catch (Exception ex){ms = null;}return ms;}/// <param name="hssfworkbook">Excel操作類</param>/// <param name="fontname">字體名</param>/// <param name="fontcolor">字體顏色</param>/// <param name="fontsize">字體大小</param>/// <returns></returns>//public static IFont GetFontStyle(HSSFWorkbook hssfworkbook, string fontfamily, HSSFColor fontcolor, int fontsize)//{// IFont font1 = hssfworkbook.CreateFont();// if (string.IsNullOrEmpty(fontfamily))// {// font1.FontName = fontfamily;// }// if (fontcolor != null)// {// font1.Color = fontcolor.Indexed;// }// font1.IsItalic = true;// font1.FontHeightInPoints = (short)fontsize;// return font1;//}/// <param name="hssfworkbook">Excel操作類</param>/// <param name="font">單元格字體</param>/// <param name="fillForegroundColor">圖案的顏色</param>/// <param name="fillPattern">圖案樣式</param>/// <param name="fillBackgroundColor">單元格背景</param>/// <param name="ha">垂直對齊方式</param>/// <param name="va">垂直對齊方式</param>/// <returns></returns>//public static ICellStyle GetCellStyle(HSSFWorkbook hssfworkbook, IFont font, NPOI.HSSF.Util.HSSFColor fillForegroundColor, FillPattern fillPattern, HSSFColor fillBackgroundColor, HorizontalAlignment ha, VerticalAlignment va)//{// ICellStyle cellstyle = hssfworkbook.CreateCellStyle();// cellstyle.FillPattern = fillPattern;// cellstyle.Alignment = ha;// cellstyle.VerticalAlignment = va;// if (fillForegroundColor != null)// {// cellstyle.FillForegroundColor = fillForegroundColor.Indexed;// }// if (fillBackgroundColor != null)// {// cellstyle.FillBackgroundColor = fillBackgroundColor.Indexed;// }// if (font != null)// {// cellstyle.SetFont(font);// }// //有邊框// cellstyle.BorderBottom = BorderStyle.Thin;// cellstyle.BorderLeft = BorderStyle.Thin;// cellstyle.BorderRight = BorderStyle.Thin;// cellstyle.BorderTop = BorderStyle.Thin;// return cellstyle;//}/// <param name="sheet">要合并單元格所在的sheet</param>/// <param name="rowstart">開始行的索引</param>/// <param name="rowend">結束行的索引</param>/// <param name="colstart">開始列的索引</param>/// <param name="colend">結束列的索引</param>public static void SetCellRangeAddress(ISheet sheet, int rowstart, int rowend, int colstart, int colend){CellRangeAddress cellRangeAddress = new CellRangeAddress(rowstart, rowend, colstart, colend);sheet.AddMergedRegion(cellRangeAddress);}} }?
轉載于:https://www.cnblogs.com/LZXX/p/8761766.html
總結
以上是生活随笔為你收集整理的c#_导出table功能的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: zabbix编译安装
- 下一篇: Linux中几个实用快捷键