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,一经查实,立即删除!

相关文章

java 协议处理器_协议处理器urlstreamhandler及contenthandler

先看段打开网页的代码&#xff1a;URL urlnew URL("http://souljava.blog.163.com/");URLConnection connectionurl.openConnection();connection.getInputStream();问题1&#xff1a;客户端浏览器怎么判断接受到的是什么数据类型&#xff1f;回答&#xff1a;java的…

自己做一个小项目python_【Python】第一个微信小项目

一、微信好友数据分析功能介绍1.爬取好友列表,显示好友昵称、性别和地域和签名, 文件保存为 xlsx 格式2.统计好友的地域分布&#xff0c;并且做成词云和可视化展示在地图上3.获取所有好友的头像&#xff0c;合并成一张大图二、需要的库1、Pyecharts&#xff1a;一个用于生成ech…

RISC-V的自定义CPU悖论

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

java计算加速减速_Javascript加速运动与减速运动

加速运动&#xff0c;即一个物体运动时速度越来越快&#xff1b;减速运动&#xff0c;即一个物体运动时速度越来越慢。现在用Javascript来模拟这两个效果&#xff0c;原理就是用setInterval或setTimeout动态改变一个元素与另外一个元素的距离&#xff0c;如xxx.style.left或xxx…

python 运维包_基础入门_Python-模块和包.运维开发中__import__动态导入最佳实践?

常规导入:import module_name[,module1,...]from module_name import [*|child[,child1,...]from module_name import [*|child[,child1,...] as alias_name注意: 导入语句可出现在程序任意位置,自定义包要实现from module_name import *的效果则此模块必须在__init__.py实现__…

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

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

Node.js教程-mysql模块

概述 在Node.js中&#xff0c;mysql模块是实现MySQL协议的JavaScript客户端工具。Node.js程序通过与MySQL建立链接&#xff0c;然后可对数据进行增、删、改、查等操作。 安装 由于mysql模块不是Node.js内置模块&#xff0c;需手动安装 npm i mysql注意&#xff1a;若MySQL服…

java 几种引用类型_Java 四种引用类型总结-Fun言

1. Java引用介绍Java从1.2版本开始引入了4种引用&#xff0c;这4种引用的级别由高到低依次为&#xff1a;强引用 > 软引用 > 弱引用 > 虚引用⑴ 强引用(Strong Reference)强引用是使用最普遍的引用&#xff0c;也是赋值的默认引用。如果一个对象具有强引用&…

JS运算符类型

一、运算符类型 1、算术运算符&#xff1a;用于各类数值运算&#xff0c;包括加()、减(-)、乘(*)、除(/)、求余(或称模运算&#xff0c;%)、自增()、自减(--)共七种。2、关系运算符&#xff1a;用于比较运算。包括大于&#xff08;>&#xff09;、小于&#xff08;<&…

python关于字符串的内置函数_Python 字符串内置函数(二)

# 2.格式化相关# ljust(width) 函数 获取固定长度&#xff0c;左对齐&#xff0c;右边不够用空格补齐# rjust(width) 函数 获取固定长度&#xff0c;右对齐&#xff0c;左边不够用空格补齐# center(width) 函数 获取固定长度&#xff0c;中间对齐&#xff0c;两边不够用空格补齐…

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

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

java中for的常规用法_Java for循环的几种用法详解

本文非常适合初学Java的程序员&#xff0c;主要是来了解一下Java中的几种for循环用法&#xff0c;分析得十分详细&#xff0c;一起来看看。J2SE 1.5提供了另一种形式的for循环。借助这种形式的for循环&#xff0c;可以用更简单地方式来遍历数组和Collection等类型的对象。本文介…

运维-替换-修改kibana徽标

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

python中的变量的作用_Python中的变量作用域

python中变量作用域包括&#xff1a;L (Local) 局部作用域&#xff0c;函数内部声明但没有使用global的变量E (Enclosing) 闭包函数外的函数中&#xff0c;def或者lambda的本地作用域G (Global) 全局作用域&#xff0c;函数中使用global声明的变量或在模块层声明的变量B (Built…

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

来源&#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;并且还提供了监…

python提取部分字符串三参数_python3 字符串属性(三)

maketrans 和 translate的用法(配合使用)下面是python的英文用法解释maketrans(x, yNone, zNone, /)Return a translation table usable for str.translate().If there is only one argument, it must be a dictionary mapping Unicodeordinals (integers) or characters to Un…

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

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

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

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

[CEOI2008] order

题目描述 有N个工作&#xff0c;M种机器&#xff0c;每种机器你可以租或者买过来. 每个工作包括若干道工序&#xff0c;每道工序需要某种机器来完成,你可以通过购买或租用机器来完成。 现在给出这些参数&#xff0c;求最大利润 输入输出格式 输入格式&#xff1a; 第一行给出 N…