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打开而已  所以在设置导出格式无能为力(如时间格式就会出现问题)

 

 

二:第二种,能改变导出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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/486356.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

RISC-V的自定义CPU悖论

来源&#xff1a;内容编译自「eejournal」&#xff0c;谢谢。随着这些年的发展&#xff0c;RISC-V的受重视程度与与日俱增。这主要因为它是免费的、灵活的&#xff0c;并且速度很快。这使RISC-V成为许多开发人员的安全便捷选择。但是您会认为RISC-V是通用RISC处理器还是定制的随…

华为宣布出售荣耀,声明来了

来源&#xff1a;澎湃新闻综合华为官网、《深圳特区报》今天&#xff0c;华为发表声明&#xff0c;整体出售荣耀业务资产。对于交割后的荣耀&#xff0c;华为不占有任何股份&#xff0c;也不参与经营管理与决策。11月17日一早&#xff0c;荣耀最终的出售方案公布。多家企业在《…

边缘计算4.0正急速驶来,你做好准备了吗?

物联网智库 整理发布导 读近十年间&#xff0c;各行各业的企业都经历着数字化技术和产品对传统生产经营模式的冲击。人工智能、大数据、区块链、自动化等技术的日渐完善&#xff0c;让企业的生产效率和业务模式发生了翻天覆地的变化。

运维-替换-修改kibana徽标

作为一名纯运维人员&#xff0c;想更改kibana的徽标。 并不能像开发一样去看源码并修改源码。 所以我们可以替换徽标。 先来一个效果图。我的版本是5.5.1。 具体的修改过程&#xff1a; 在kibana安装路径下面。 optimize/bundles/ 0cebf3d61338c454670b1c5bdf5d6d8d.svg 这…

欧拉公式——真正的宇宙第一公式

来源&#xff1a;数学中国欧拉公式是数学里最令人着迷的公式之一&#xff0c;它将数学里最重要的几个常数联系到了一起&#xff1a;两个超越数&#xff1a;自然对数的底e&#xff0c;圆周率π&#xff1b;两个单位&#xff1a;虚数单位i和自然数的单位1&#xff0c;以及数学里常…

SpringBoot入门篇--整合mybatis+generator自动生成代码+druid连接池+PageHelper分页插件

我们这一一篇博客讲的是如何整合Springboot和Mybatis框架&#xff0c;然后使用generator自动生成mapper&#xff0c;pojo等文件。然后再使用阿里巴巴提供的开源连接池druid&#xff0c;这个连接池的好处我就不说了&#xff0c;集合了所有连接池的好处&#xff0c;并且还提供了监…

java实现qq抢红包_Java实现抢红包功用

用多线程模仿多人一起抢红包。服务端将玩家发出的红包保存在一个行列里&#xff0c;然后用Job守时将红包信息推送给玩家。每一批玩家的抢红包恳求&#xff0c;其实操作的都是从行列中弹出的第一个红包元素&#xff0c;但当时的红包数量为空的时分&#xff0c;主动弹出下一个红包…

芯片里面100多亿个晶体管是如何安装上去的?

来源&#xff1a;金属加工如今随着芯片制程的不断提升&#xff0c;芯片中可以有100多亿个晶体管&#xff0c;如此之多的晶体管&#xff0c;究竟是如何安上去的呢&#xff1f;1当芯片被不停地放大&#xff0c;里面宛如一座巨大的城市。这是一个Top-down View 的SEM照片&#xff…

response.end后抛了异常_(七)异常处理

(七)异常处理异常异常的体系结构java.lang.Throwable|-----java.lang.Error&#xff1a;一般不便携针对性的代码进行处理|-----java.lang.Exception&#xff1a;可以进行异常的处理|-----编译时异常&#xff08;checked|-----IOException|-----FileNotFoundException|-----Clas…

AI+视频分析:实时监测无处不在的安全风险

来源丨Forbes作者丨Louis Columbus编译丨科技行者纵观2020年运营层面的诸多挑战&#xff0c;公共事业企业已经意识到对其所运营的物理及网络安全体系进行360度全方位审视的重要意义。最近&#xff0c;由Gartner发布的调查报告显示&#xff0c;94%的北美CIO认为&#xff0c;对偏…

python 绘图的背景颜色不要_matplotlib自定义添加 “哆啦A梦”背景图,这个操作真牛逼!...

为什么需要加星标&#xff1f;由于微信公众号出现了 “乱序” 排列的状况&#xff0c;也就是说&#xff1a;文章不会按照 “时间顺序” 推送给你。那么朋友们就不能第一时间&#xff0c;收到我的干货。因此希望您抽出一分钟&#xff0c;完成如下三步。数据分析与统计学之美原创…

台积电2nm工艺重大突破!

来源&#xff1a;万物智能视界根据最新报道&#xff0c;台积电已经在2nm工艺上取得一项重大的内部突破&#xff0c;虽未披露细节&#xff0c;但是据此乐观预计&#xff0c;2nm工艺有望在2023年下半年进行风险性试产&#xff0c;2024年就能步入量产阶段。台积电还表示&#xff0…

png文件合并_png格式图片和jpg格式图片有什么区别?

两个格式的图片群文件有一定的相似之处&#xff0c;png是无损压缩&#xff0c;可以在PS中重新编辑。.jpg格式是一种压缩的图片文件&#xff0c;不能再次编辑&#xff0c;而且在解析度上也是不如.png格式。具体介绍如下&#xff1a;1、png是无损压缩&#xff0c;png即可移植网络…

python环境变量的配置_python基础教程-第一讲-带你进入python的世界

python是一门非常流行的语言&#xff0c;在前段时间网上流传的地产大佬潘石屹宣布要开始学习Python编程&#xff0c;这着实让python又火了一把&#xff0c;但确实反映出python的火热程度 。在2019年12月的世界编程语言排行榜中&#xff0c;python排名第三。2019年12月语言排行榜…

java单终端登陆_配置终端服务单一登录

配置终端服务单一登录配置终端服务单一登录单一登录是一种身份验证方法&#xff0c;允许具有域帐户的用户使用密码或智能卡登录一次&#xff0c;然后&#xff0c;不再要求其提供凭据即可访问远程服务器。若要在终端服务中实现单一登录功能&#xff0c;请确保满足下列要求&#…

Mybatis逆向工程的pojo实现序列化接口代码

情景如下&#xff0c;这两天在做一个分布式的项目&#xff0c;使用了Alibaba的dubbo作为通信工具&#xff0c;zookeeper作为register&#xff0c;由于dubbo是基于socket协议的&#xff0c;所以在进行pojo传输的时候报了异常&#xff0c;因为pojo没有实现序列化接口&#xff0c;…

重磅!2020年全球高被引科学家名单出炉!

来源&#xff1a;科睿唯安、青塔英国伦敦时间11月18日&#xff0c;科睿唯安公布了2020年度“高被引科学家”名单。入榜这份备受期待的名单的自然科学家和社会科学家均发表了多篇高被引论文&#xff0c; 其被引频次位于同学科前1%&#xff0c;彰显了他们在同行之中的重要学术影响…

机器学习—K近邻

一、算法原理 还是图片格式~ 二、sklearn实现 import pandas as pd import numpy as np import matplotlib.pyplot as plt import matplotlib as mpl import seaborn as sns mpl.rcParams[font.sans-serif] [uSimHei] mpl.rcParams[axes.unicode_minus] False from sklearn.d…

华人教授世界一流大学观察报告:斯坦福师生吃饭时,谈论的都是什么话题?...

石毓智&#xff0c;斯坦福大学博士、湖南师范大学特聘教授、新加坡国立大学终身教职。来源&#xff1a;墨香学术 微信&#xff1a;moxiangxueshu编辑 ∑Gemini只有短短120年历史的斯坦福大学&#xff0c;已有近30人获得诺奖&#xff0c;不要说世界上其他大学难以匹敌&#xff0…

tcp连接工具_基于Swoole如何搭建TCP服务,你掌握了吗?

本节将会讲解以下3个问题&#xff1a;通过Swoole如何搭建TCP服务&#xff1f;通过Swoole如何搭建TCP客户端&#xff1f;通过Swoole搭建的TCP服务&#xff0c;更深入理解Swoole的事件驱动模式通过Swoole可以快速创建一个TCP服务&#xff0c;新建一个文件命名为 tcp_server.php&a…