using System; using System.Collections.Generic; using System.Data; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Web; using NPOI.HSSF.UserModel; using NPOI.SS.UserModel; using NPOI.XSSF.UserModel; using System.Web.UI.WebControls; using SuperMap.RealEstate.Utility; using SuperMap.RealEstate.Web.UI.WebControls; namespace HZQR.Common { public class ExcelHelper { private string fileName = null; //文件名 private IWorkbook workbook = null; private FileStream fs = null; private bool disposed; #region 方法 -> 导出excel public int DataTableToExcel(string FileName, DataTable data, string sheetName, bool isColumnWritten) { int i = 0; int j = 0; int count = 0; ISheet sheet = null; if (!string.IsNullOrWhiteSpace(FileName) && (FileName.Contains("
") || FileName.Contains("
"))) { FileName = FileName.Replace("
", "").Replace("
", ""); } if (!string.IsNullOrWhiteSpace(sheetName) && (sheetName.Contains("
") || sheetName.Contains("
"))) { sheetName = sheetName.Replace("
", "").Replace("
", ""); } if (fileName == null) { workbook = new NPOI.HSSF.UserModel.HSSFWorkbook(); //NPOI.SS.UserModel.ISheet sheet = book.CreateSheet("Sheet1"); } else { fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite); if (fileName.IndexOf(".xlsx") > 0) // 2007版本 workbook = new XSSFWorkbook(); else if (fileName.IndexOf(".xls") > 0) // 2003版本 workbook = new HSSFWorkbook(); } try { if (workbook != null) { sheet = workbook.CreateSheet(sheetName); } else { return -1; } if (isColumnWritten == true) //写入DataTable的列名 { IRow row = sheet.CreateRow(0); for (j = 0; j < data.Columns.Count; ++j) { row.CreateCell(j).SetCellValue(data.Columns[j].ColumnName); } count = 1; } else { count = 0; } for (i = 0; i < data.Rows.Count; ++i) { IRow row = sheet.CreateRow(count); for (j = 0; j < data.Columns.Count; ++j) { row.CreateCell(j).SetCellValue(Utils.ChangeHtmlToString(data.Rows[i][j].ToString())); } ++count; } #region 自动适应中文宽度 //获取当前列的宽度,然后对比本列的长度,取最大值 for (int columnNum = 0; columnNum <= data.Rows.Count; columnNum++) { int columnWidth = sheet.GetColumnWidth(columnNum) / 256; for (int rowNum = 1; rowNum <= sheet.LastRowNum; rowNum++) { IRow currentRow; //当前行未被使用过 if (sheet.GetRow(rowNum) == null) { currentRow = sheet.CreateRow(rowNum); } else { currentRow = sheet.GetRow(rowNum); } if (currentRow.GetCell(columnNum) != null) { ICell currentCell = currentRow.GetCell(columnNum); int length = Encoding.Default.GetBytes(currentCell.ToString()).Length; if (columnWidth < length) { columnWidth = length; } } } //sheet.SetColumnWidth(columnNum, columnWidth * 256); //列宽ColumnWidth的限制255个字符,以一个字符的1/256的宽度作为一个单位。 int colWidth = columnWidth * 256; if (colWidth < 255 * 256) { sheet.SetColumnWidth(columnNum, colWidth); } else { sheet.SetColumnWidth(columnNum, 6000); } } #endregion // 写入到客户端 System.IO.MemoryStream ms = new System.IO.MemoryStream(); workbook.Write(ms); //解决360浏览器导出Excel的文件名乱码 FileName = System.Web.HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8); HttpContext.Current.Response.Clear(); HttpContext.Current.Response.Buffer = true; HttpContext.Current.Response.Charset = "utf-8"; HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");//设置输出流为简体中文 HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format( "attachment; filename=" + FileName + "_{0}.xls", DateTime.Now.ToString("yyyyMMddHHmmssfff"))); HttpContext.Current.Response.BinaryWrite(ms.ToArray()); HttpContext.Current.Response.ContentType = "application/ms-excel";//设置输出文件类型为excel文件。 HttpContext.Current.Response.End(); workbook = null; ms.Close(); ms.Dispose(); return count; } catch (Exception ex) { Console.WriteLine("Exception: " + ex.Message); return -1; } } /// /// 导出excel /// /// 标题 /// 统计时间(表单右上角) /// 制单人(表单左下角) /// 制单时间(表单右下角) /// 表单表头 /// 文件名称 /// 表单数据源 /// excel的表格名称 /// 表单表头是否显示为_title的内容 /// 表单表头是否去除重复内容, /// 如第一行显示“合计”,第二行显示“合计金额”,若changeColumnName为true则第二行显示为“金额” /// public int DataTableToExcel(string Title, string StaticTime, string OrderMaker, string MakingTime, Dictionary _title, string FileName, DataTable data, string sheetName, bool isColumnWritten, bool changeColumnName = true) { int i = 0; int j = 0; int count = 0; ISheet sheet = null; if (fileName == null) { workbook = new NPOI.HSSF.UserModel.HSSFWorkbook(); //NPOI.SS.UserModel.ISheet sheet = book.CreateSheet("Sheet1"); } else { fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite); if (fileName.IndexOf(".xlsx") > 0) // 2007版本 workbook = new XSSFWorkbook(); else if (fileName.IndexOf(".xls") > 0) // 2003版本 workbook = new HSSFWorkbook(); } //IDataFormat format = workbook.CreateDataFormat(); ICellStyle cellRightStyle = workbook.CreateCellStyle(); cellRightStyle.Alignment = HorizontalAlignment.Right; cellRightStyle.VerticalAlignment = VerticalAlignment.Center; //cellRightStyle.DataFormat = format.GetFormat("¥#,##0"); ICellStyle cellCenterStyle = workbook.CreateCellStyle(); cellCenterStyle.Alignment = HorizontalAlignment.Center; cellCenterStyle.VerticalAlignment = VerticalAlignment.Center; try { if (workbook != null) { sheet = workbook.CreateSheet(sheetName); } else { return -1; } if (Title != "") { IRow titleRow = sheet.CreateRow(count); titleRow.Height = 1000; ICell titleCell = titleRow.CreateCell(0); titleCell.SetCellValue(Title.Replace("
", "\n")); ICellStyle cellStyle = workbook.CreateCellStyle(); IFont titleFont = workbook.CreateFont(); titleFont.Boldweight = (short)FontBoldWeight.Bold; titleFont.FontHeight = 18 * 18; cellStyle.SetFont(titleFont); cellStyle.Alignment = HorizontalAlignment.Center; cellStyle.VerticalAlignment = VerticalAlignment.Center; cellStyle.WrapText = true; sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(count, count, 0, data.Columns.Count - 1)); titleCell.CellStyle = cellStyle; count++; } if (StaticTime != "") { IRow staticTimeRow = sheet.CreateRow(count); ICell staticTimeCell = staticTimeRow.CreateCell(0); staticTimeCell.SetCellValue(StaticTime); ICellStyle cellStyle = workbook.CreateCellStyle(); cellStyle.Alignment = HorizontalAlignment.Right; cellStyle.VerticalAlignment = VerticalAlignment.Center; sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(count, count, 0, data.Columns.Count - 1)); staticTimeCell.CellStyle = cellStyle; count++; } List _list = new List(); if (_title != null && _title.Count > 0) { int columns = -1; int cells = 0; IRow Rows = sheet.CreateRow(count); //ICellStyle cellStyle = workbook.CreateCellStyle(); //cellStyle.Alignment = HorizontalAlignment.Center; //cellStyle.VerticalAlignment = VerticalAlignment.Center; foreach (var item in _title) { columns += item.Value; ICell Cells = Rows.CreateCell(cells); Cells.SetCellValue(item.Key); sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(count, count, item.Value == 0 ? 0 : columns - (item.Value - 1), columns)); Cells.CellStyle = cellCenterStyle; cells += item.Value; for (int n = 0; n < item.Value; n++) { _list.Add(item.Key.Trim()); } } count++; } if (isColumnWritten == true) //写入DataTable的列名 { IRow row = sheet.CreateRow(count); //ICellStyle cellStyle = workbook.CreateCellStyle(); //cellStyle.Alignment = HorizontalAlignment.Center; //cellStyle.VerticalAlignment = VerticalAlignment.Center; for (j = 0; j < data.Columns.Count; ++j) { ICell Cells = row.CreateCell(j); if (_list != null && _list.Count > j && changeColumnName) { Cells.SetCellValue(data.Columns[j].ColumnName.Replace(_list[j], "")); } else { Cells.SetCellValue(data.Columns[j].ColumnName); } Cells.CellStyle = cellCenterStyle; } count++; } for (i = 0; i < data.Rows.Count; ++i) { IRow row = sheet.CreateRow(count); for (j = 0; j < data.Columns.Count; ++j) { ICell Cells = row.CreateCell(j); //Cells.SetCellValue(data.Rows[i][j].ToString()); double _price; if (double.TryParse(data.Rows[i][j].ToString(), out _price) && (data.Columns[j].DataType == typeof(decimal) || data.Columns[j].DataType == typeof(int) || data.Columns[j].DataType == typeof(double))) { Cells.SetCellValue(_price); Cells.CellStyle = cellRightStyle; } else { Cells.SetCellValue(Utils.ChangeHtmlToString(data.Rows[i][j].ToString())); Cells.CellStyle = cellCenterStyle; } //row.CreateCell(j).SetCellValue(data.Rows[i][j].ToString()); } ++count; } if (OrderMaker != "" && MakingTime != "") { IRow OrderRow = sheet.CreateRow(count); //ICellStyle cellStyle = workbook.CreateCellStyle(); //cellStyle.VerticalAlignment = VerticalAlignment.Center; //cellStyle.Alignment = HorizontalAlignment.Center; ICell OrderMakerCell = OrderRow.CreateCell(0); OrderMakerCell.SetCellValue(OrderMaker); ICell MakingTimeCell = OrderRow.CreateCell(data.Columns.Count - 2); MakingTimeCell.SetCellValue(MakingTime); sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(count, count, 0, 1)); sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(count, count, data.Columns.Count - 2, data.Columns.Count - 1)); OrderMakerCell.CellStyle = cellCenterStyle; MakingTimeCell.CellStyle = cellCenterStyle; count++; } #region 自动适应中文宽度 //获取当前列的宽度,然后对比本列的长度,取最大值 for (int columnNum = 0; columnNum <= data.Rows.Count; columnNum++) { int columnWidth = sheet.GetColumnWidth(columnNum) / 256; for (int rowNum = 1; rowNum <= sheet.LastRowNum; rowNum++) { IRow currentRow; //当前行未被使用过 if (sheet.GetRow(rowNum) == null) { currentRow = sheet.CreateRow(rowNum); } else { currentRow = sheet.GetRow(rowNum); } if (currentRow.GetCell(columnNum) != null) { ICell currentCell = currentRow.GetCell(columnNum); int length = Encoding.Default.GetBytes(currentCell.ToString()).Length; if (columnWidth < length) { columnWidth = length; } } } //sheet.SetColumnWidth(columnNum, columnWidth * 256); //列宽ColumnWidth的限制255个字符,以一个字符的1/256的宽度作为一个单位。 int colWidth = columnWidth * 256; if (colWidth < 255 * 256) { sheet.SetColumnWidth(columnNum, colWidth); } else { sheet.SetColumnWidth(columnNum, 6000); } } #endregion // 写入到客户端 System.IO.MemoryStream ms = new System.IO.MemoryStream(); workbook.Write(ms); //解决360浏览器导出Excel的文件名乱码 FileName = System.Web.HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8); HttpContext.Current.Response.Clear(); HttpContext.Current.Response.Buffer = true; HttpContext.Current.Response.Charset = "utf-8"; HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");//设置输出流为简体中文 HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format( "attachment; filename=" + FileName + "_{0}.xls", DateTime.Now.ToString("yyyyMMddHHmmssfff"))); HttpContext.Current.Response.BinaryWrite(ms.ToArray()); HttpContext.Current.Response.ContentType = "application/ms-excel";//设置输出文件类型为excel文件。 HttpContext.Current.Response.End(); workbook = null; ms.Close(); ms.Dispose(); return count; } catch (Exception ex) { ErrorLogHelper.Write(ex); return -1; } } public int DataTableToExcel(string Title, string StaticTime, string OrderMaker, string MakingTime, Dictionary _title, Dictionary _title2, string FileName, DataTable data, string sheetName, bool isColumnWritten, bool changeColumnName = true) { int i = 0; int j = 0; int count = 0; ISheet sheet = null; if (fileName == null) { workbook = new NPOI.HSSF.UserModel.HSSFWorkbook(); //NPOI.SS.UserModel.ISheet sheet = book.CreateSheet("Sheet1"); } else { fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite); if (fileName.IndexOf(".xlsx") > 0) // 2007版本 workbook = new XSSFWorkbook(); else if (fileName.IndexOf(".xls") > 0) // 2003版本 workbook = new HSSFWorkbook(); } //IDataFormat format = workbook.CreateDataFormat(); ICellStyle cellRightStyle = workbook.CreateCellStyle(); cellRightStyle.Alignment = HorizontalAlignment.Right; cellRightStyle.VerticalAlignment = VerticalAlignment.Center; //cellRightStyle.DataFormat = format.GetFormat("¥#,##0"); ICellStyle cellCenterStyle = workbook.CreateCellStyle(); cellCenterStyle.Alignment = HorizontalAlignment.Center; cellCenterStyle.VerticalAlignment = VerticalAlignment.Center; try { if (workbook != null) { sheet = workbook.CreateSheet(sheetName); } else { return -1; } if (Title != "") { IRow titleRow = sheet.CreateRow(count); titleRow.Height = 1000; ICell titleCell = titleRow.CreateCell(0); titleCell.SetCellValue(Title.Replace("
", "\n")); ICellStyle cellStyle = workbook.CreateCellStyle(); IFont titleFont = workbook.CreateFont(); titleFont.Boldweight = (short)FontBoldWeight.Bold; titleFont.FontHeight = 18 * 18; cellStyle.SetFont(titleFont); cellStyle.Alignment = HorizontalAlignment.Center; cellStyle.VerticalAlignment = VerticalAlignment.Center; cellStyle.WrapText = true; sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(count, count, 0, data.Columns.Count - 1)); titleCell.CellStyle = cellStyle; count++; } if (StaticTime != "") { IRow staticTimeRow = sheet.CreateRow(count); ICell staticTimeCell = staticTimeRow.CreateCell(0); staticTimeCell.SetCellValue(StaticTime); ICellStyle cellStyle = workbook.CreateCellStyle(); cellStyle.Alignment = HorizontalAlignment.Right; cellStyle.VerticalAlignment = VerticalAlignment.Center; sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(count, count, 0, data.Columns.Count - 1)); staticTimeCell.CellStyle = cellStyle; count++; } List _list = new List(); if (_title != null && _title.Count > 0) { int columns = -1; int cells = 0; IRow Rows = sheet.CreateRow(count); //ICellStyle cellStyle = workbook.CreateCellStyle(); //cellStyle.Alignment = HorizontalAlignment.Center; //cellStyle.VerticalAlignment = VerticalAlignment.Center; foreach (var item in _title) { columns += item.Value; ICell Cells = Rows.CreateCell(cells); Cells.SetCellValue(item.Key); sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(count, count, item.Value == 0 ? 0 : columns - (item.Value - 1), columns)); Cells.CellStyle = cellCenterStyle; cells += item.Value; for (int n = 0; n < item.Value; n++) { _list.Add(item.Key.Trim()); } } count++; } List _list2 = new List(); if (_title2 != null && _title2.Count > 0) { int columns = -1; int cells = 0; IRow Rows = sheet.CreateRow(count); //ICellStyle cellStyle = workbook.CreateCellStyle(); //cellStyle.Alignment = HorizontalAlignment.Center; //cellStyle.VerticalAlignment = VerticalAlignment.Center; foreach (var item in _title2) { columns += item.Value; ICell Cells = Rows.CreateCell(cells); Cells.SetCellValue(item.Key); sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(count, count, item.Value == 0 ? 0 : columns - (item.Value - 1), columns)); Cells.CellStyle = cellCenterStyle; cells += item.Value; for (int n = 0; n < item.Value; n++) { _list2.Add(item.Key.Trim()); } } count++; } if (isColumnWritten == true) //写入DataTable的列名 { IRow row = sheet.CreateRow(count); //ICellStyle cellStyle = workbook.CreateCellStyle(); //cellStyle.Alignment = HorizontalAlignment.Center; //cellStyle.VerticalAlignment = VerticalAlignment.Center; for (j = 0; j < data.Columns.Count; ++j) { ICell Cells = row.CreateCell(j); if (_list != null && _list.Count > j && changeColumnName) { Cells.SetCellValue(data.Columns[j].ColumnName.Replace(_list[j], "")); } else { Cells.SetCellValue(data.Columns[j].ColumnName); } Cells.CellStyle = cellCenterStyle; } count++; } for (i = 0; i < data.Rows.Count; ++i) { IRow row = sheet.CreateRow(count); for (j = 0; j < data.Columns.Count; ++j) { ICell Cells = row.CreateCell(j); //Cells.SetCellValue(data.Rows[i][j].ToString()); double _price; if (double.TryParse(data.Rows[i][j].ToString(), out _price) && (data.Columns[j].DataType == typeof(decimal) || data.Columns[j].DataType == typeof(int) || data.Columns[j].DataType == typeof(double))) { Cells.SetCellValue(_price); Cells.CellStyle = cellRightStyle; } else { Cells.SetCellValue(Utils.ChangeHtmlToString(data.Rows[i][j].ToString())); Cells.CellStyle = cellCenterStyle; } //row.CreateCell(j).SetCellValue(data.Rows[i][j].ToString()); } ++count; } if (OrderMaker != "" && MakingTime != "") { IRow OrderRow = sheet.CreateRow(count); //ICellStyle cellStyle = workbook.CreateCellStyle(); //cellStyle.VerticalAlignment = VerticalAlignment.Center; //cellStyle.Alignment = HorizontalAlignment.Center; ICell OrderMakerCell = OrderRow.CreateCell(0); OrderMakerCell.SetCellValue(OrderMaker); ICell MakingTimeCell = OrderRow.CreateCell(data.Columns.Count - 2); MakingTimeCell.SetCellValue(MakingTime); sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(count, count, 0, 1)); sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(count, count, data.Columns.Count - 2, data.Columns.Count - 1)); OrderMakerCell.CellStyle = cellCenterStyle; MakingTimeCell.CellStyle = cellCenterStyle; count++; } #region 自动适应中文宽度 //获取当前列的宽度,然后对比本列的长度,取最大值 for (int columnNum = 0; columnNum <= data.Rows.Count; columnNum++) { int columnWidth = sheet.GetColumnWidth(columnNum) / 256; for (int rowNum = 1; rowNum <= sheet.LastRowNum; rowNum++) { IRow currentRow; //当前行未被使用过 if (sheet.GetRow(rowNum) == null) { currentRow = sheet.CreateRow(rowNum); } else { currentRow = sheet.GetRow(rowNum); } if (currentRow.GetCell(columnNum) != null) { ICell currentCell = currentRow.GetCell(columnNum); int length = Encoding.Default.GetBytes(currentCell.ToString()).Length; if (columnWidth < length) { columnWidth = length; } } } //sheet.SetColumnWidth(columnNum, columnWidth * 256); //列宽ColumnWidth的限制255个字符,以一个字符的1/256的宽度作为一个单位。 int colWidth = columnWidth * 256; if (colWidth < 255 * 256) { sheet.SetColumnWidth(columnNum, colWidth); } else { sheet.SetColumnWidth(columnNum, 6000); } } #endregion // 写入到客户端 System.IO.MemoryStream ms = new System.IO.MemoryStream(); workbook.Write(ms); //解决360浏览器导出Excel的文件名乱码 FileName = System.Web.HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8); HttpContext.Current.Response.Clear(); HttpContext.Current.Response.Buffer = true; HttpContext.Current.Response.Charset = "utf-8"; HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");//设置输出流为简体中文 HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format( "attachment; filename=" + FileName + "_{0}.xls", DateTime.Now.ToString("yyyyMMddHHmmssfff"))); HttpContext.Current.Response.BinaryWrite(ms.ToArray()); HttpContext.Current.Response.ContentType = "application/ms-excel";//设置输出文件类型为excel文件。 HttpContext.Current.Response.End(); workbook = null; ms.Close(); ms.Dispose(); return count; } catch (Exception ex) { ErrorLogHelper.Write(ex); return -1; } } public int DataTableToExcel(string Title, string StaticTime, string OrderMaker, string MakingTime, Dictionary _title, string FileName, DataTable data, string sheetName, string OpinionName, bool isColumnWritten) { int i = 0; int j = 0; int count = 0; ISheet sheet = null; if (fileName == null) { workbook = new NPOI.HSSF.UserModel.HSSFWorkbook(); //NPOI.SS.UserModel.ISheet sheet = book.CreateSheet("Sheet1"); } else { fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite); if (fileName.IndexOf(".xlsx") > 0) // 2007版本 workbook = new XSSFWorkbook(); else if (fileName.IndexOf(".xls") > 0) // 2003版本 workbook = new HSSFWorkbook(); } //IDataFormat format = workbook.CreateDataFormat(); ICellStyle cellRightStyle = workbook.CreateCellStyle(); cellRightStyle.Alignment = HorizontalAlignment.Right; cellRightStyle.VerticalAlignment = VerticalAlignment.Center; //cellRightStyle.DataFormat = format.GetFormat("¥#,##0"); ICellStyle cellCenterStyle = workbook.CreateCellStyle(); cellCenterStyle.Alignment = HorizontalAlignment.Center; cellCenterStyle.VerticalAlignment = VerticalAlignment.Center; try { if (workbook != null) { sheet = workbook.CreateSheet(sheetName); } else { return -1; } if (Title != "") { IRow titleRow = sheet.CreateRow(count); titleRow.Height = 1000; ICell titleCell = titleRow.CreateCell(0); titleCell.SetCellValue(Title.Replace("
", "\n")); ICellStyle cellStyle = workbook.CreateCellStyle(); IFont titleFont = workbook.CreateFont(); titleFont.Boldweight = (short)FontBoldWeight.Bold; titleFont.FontHeight = 18 * 18; cellStyle.SetFont(titleFont); cellStyle.Alignment = HorizontalAlignment.Center; cellStyle.VerticalAlignment = VerticalAlignment.Center; cellStyle.WrapText = true; sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(count, count, 0, data.Columns.Count - 1)); titleCell.CellStyle = cellStyle; count++; } if (StaticTime != "") { IRow staticTimeRow = sheet.CreateRow(count); ICell staticTimeCell = staticTimeRow.CreateCell(0); staticTimeCell.SetCellValue(StaticTime); ICellStyle cellStyle = workbook.CreateCellStyle(); cellStyle.Alignment = HorizontalAlignment.Right; cellStyle.VerticalAlignment = VerticalAlignment.Center; sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(count, count, 0, data.Columns.Count - 1)); staticTimeCell.CellStyle = cellStyle; count++; } List _list = new List(); if (_title != null && _title.Count > 0) { int columns = -1; int cells = 0; IRow Rows = sheet.CreateRow(count); //ICellStyle cellStyle = workbook.CreateCellStyle(); //cellStyle.Alignment = HorizontalAlignment.Center; //cellStyle.VerticalAlignment = VerticalAlignment.Center; foreach (var item in _title) { columns += item.Value; ICell Cells = Rows.CreateCell(cells); Cells.SetCellValue(item.Key); sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(count, count, item.Value == 0 ? 0 : columns - (item.Value - 1), columns)); Cells.CellStyle = cellCenterStyle; cells += item.Value; for (int n = 0; n < item.Value; n++) { _list.Add(item.Key.Trim()); } } count++; } if (isColumnWritten == true) //写入DataTable的列名 { IRow row = sheet.CreateRow(count); //ICellStyle cellStyle = workbook.CreateCellStyle(); //cellStyle.Alignment = HorizontalAlignment.Center; //cellStyle.VerticalAlignment = VerticalAlignment.Center; for (j = 0; j < data.Columns.Count; ++j) { ICell Cells = row.CreateCell(j); if (_list != null && _list.Count > j) { Cells.SetCellValue(data.Columns[j].ColumnName.Replace(_list[j], "")); } else { Cells.SetCellValue(data.Columns[j].ColumnName); } Cells.CellStyle = cellCenterStyle; } count++; } for (i = 0; i < data.Rows.Count; ++i) { IRow row = sheet.CreateRow(count); for (j = 0; j < data.Columns.Count; ++j) { ICell Cells = row.CreateCell(j); //Cells.SetCellValue(data.Rows[i][j].ToString()); double _price; if (double.TryParse(data.Rows[i][j].ToString(), out _price) && (data.Columns[j].DataType == typeof(decimal) || data.Columns[j].DataType == typeof(int) || data.Columns[j].DataType == typeof(double))) { Cells.SetCellValue(_price); Cells.CellStyle = cellRightStyle; } else { Cells.SetCellValue(Utils.ChangeHtmlToString(data.Rows[i][j].ToString())); Cells.CellStyle = cellCenterStyle; } //row.CreateCell(j).SetCellValue(data.Rows[i][j].ToString()); } ++count; } if (OpinionName != "") { ICellStyle cellCenterStyles = workbook.CreateCellStyle(); cellCenterStyles.Alignment = HorizontalAlignment.Left; cellCenterStyles.VerticalAlignment = VerticalAlignment.Top; IRow OrderRow = sheet.CreateRow(count); ICell OpinionCell = OrderRow.CreateCell(0); OpinionCell.SetCellValue(OpinionName); sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(count, count + 5, 0, data.Columns.Count - 1)); OpinionCell.CellStyle = cellCenterStyles; count += 6; } if (OrderMaker != "" && MakingTime != "") { IRow OrderRow = sheet.CreateRow(count); //ICellStyle cellStyle = workbook.CreateCellStyle(); //cellStyle.VerticalAlignment = VerticalAlignment.Center; //cellStyle.Alignment = HorizontalAlignment.Center; ICell OrderMakerCell = OrderRow.CreateCell(0); OrderMakerCell.SetCellValue(OrderMaker); ICell MakingTimeCell = OrderRow.CreateCell(data.Columns.Count - 2); MakingTimeCell.SetCellValue(MakingTime); sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(count, count, 0, 1)); sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(count, count, data.Columns.Count - 2, data.Columns.Count - 1)); OrderMakerCell.CellStyle = cellCenterStyle; MakingTimeCell.CellStyle = cellCenterStyle; count++; } #region 自动适应中文宽度 //获取当前列的宽度,然后对比本列的长度,取最大值 for (int columnNum = 0; columnNum <= data.Rows.Count; columnNum++) { int columnWidth = sheet.GetColumnWidth(columnNum) / 256; for (int rowNum = 1; rowNum <= sheet.LastRowNum; rowNum++) { IRow currentRow; //当前行未被使用过 if (sheet.GetRow(rowNum) == null) { currentRow = sheet.CreateRow(rowNum); } else { currentRow = sheet.GetRow(rowNum); } if (currentRow.GetCell(columnNum) != null) { ICell currentCell = currentRow.GetCell(columnNum); int length = Encoding.Default.GetBytes(currentCell.ToString()).Length; if (columnWidth < length) { columnWidth = length; } } } //sheet.SetColumnWidth(columnNum, columnWidth * 256); //列宽ColumnWidth的限制255个字符,以一个字符的1/256的宽度作为一个单位。 int colWidth = columnWidth * 256; if (colWidth < 255 * 256) { sheet.SetColumnWidth(columnNum, colWidth); } else { sheet.SetColumnWidth(columnNum, 6000); } } #endregion // 写入到客户端 System.IO.MemoryStream ms = new System.IO.MemoryStream(); workbook.Write(ms); //解决360浏览器导出Excel的文件名乱码 FileName = System.Web.HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8); HttpContext.Current.Response.Clear(); HttpContext.Current.Response.Buffer = true; HttpContext.Current.Response.Charset = "utf-8"; HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");//设置输出流为简体中文 HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format( "attachment; filename=" + FileName + "_{0}.xls", DateTime.Now.ToString("yyyyMMddHHmmssfff"))); HttpContext.Current.Response.BinaryWrite(ms.ToArray()); HttpContext.Current.Response.ContentType = "application/ms-excel";//设置输出文件类型为excel文件。 HttpContext.Current.Response.End(); workbook = null; ms.Close(); ms.Dispose(); return count; } catch (Exception ex) { ErrorLogHelper.Write(ex); return -1; } } /// /// 导出excel /// /// 标题 /// 统计方式(表单左上角) /// 统计时间(表单右上角) /// 制单人(表单左下角) /// 制单时间(表单右下角) /// 表单表头 /// 文件名称 /// 表单数据源 /// excel的表格名称 /// 表单表头是否显示为_title的内容 /// 表单表头是否去除重复内容, /// 如第一行显示“合计”,第二行显示“合计金额”,若changeColumnName为true则第二行显示为“金额” /// public int DataTableToExcel(string Title, string staticMode, string staticTime, string OrderMaker, string MakingTime, Dictionary _title, string FileName, DataTable data, string sheetName, bool isColumnWritten, bool changeColumnName = true) { int i = 0; int j = 0; int count = 0; ISheet sheet = null; if (fileName == null) { workbook = new NPOI.HSSF.UserModel.HSSFWorkbook(); } else { fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite); if (fileName.IndexOf(".xlsx") > 0) // 2007版本 workbook = new XSSFWorkbook(); else if (fileName.IndexOf(".xls") > 0) // 2003版本 workbook = new HSSFWorkbook(); } ICellStyle cellLeftStyle = workbook.CreateCellStyle(); cellLeftStyle.Alignment = HorizontalAlignment.Left; cellLeftStyle.VerticalAlignment = VerticalAlignment.Center; ICellStyle cellRightStyle = workbook.CreateCellStyle(); cellRightStyle.Alignment = HorizontalAlignment.Right; cellRightStyle.VerticalAlignment = VerticalAlignment.Center; ICellStyle cellCenterStyle = workbook.CreateCellStyle(); cellCenterStyle.Alignment = HorizontalAlignment.Center; cellCenterStyle.VerticalAlignment = VerticalAlignment.Center; try { if (workbook != null) { sheet = workbook.CreateSheet(sheetName); } else { return -1; } if (Title != "") { IRow titleRow = sheet.CreateRow(count); titleRow.Height = 1000; ICell titleCell = titleRow.CreateCell(0); titleCell.SetCellValue(Title.Replace("
", "\n").Replace("
", "\n").Replace("
", "\n")); ICellStyle cellStyle = workbook.CreateCellStyle(); IFont titleFont = workbook.CreateFont(); titleFont.Boldweight = (short)FontBoldWeight.Bold; titleFont.FontHeight = 18 * 18; cellStyle.SetFont(titleFont); cellStyle.Alignment = HorizontalAlignment.Center; cellStyle.VerticalAlignment = VerticalAlignment.Center; cellStyle.WrapText = true; sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(count, count, 0, data.Columns.Count - 1)); titleCell.CellStyle = cellStyle; count++; } if (!string.IsNullOrWhiteSpace(staticMode) || !string.IsNullOrWhiteSpace(staticTime)) { if (string.IsNullOrWhiteSpace(staticMode)) { IRow staticTimeRow = sheet.CreateRow(count); ICell staticTimeCell = staticTimeRow.CreateCell(0); staticTimeCell.SetCellValue(staticTime); ICellStyle cellStyle = workbook.CreateCellStyle(); cellStyle.Alignment = HorizontalAlignment.Right; cellStyle.VerticalAlignment = VerticalAlignment.Center; sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(count, count, 0, data.Columns.Count - 1)); staticTimeCell.CellStyle = cellStyle; } else if (string.IsNullOrWhiteSpace(staticTime)) { IRow staticTimeRow = sheet.CreateRow(count); ICell staticTimeCell = staticTimeRow.CreateCell(0); staticTimeCell.SetCellValue(staticMode); ICellStyle cellStyle = workbook.CreateCellStyle(); cellStyle.Alignment = HorizontalAlignment.Left; cellStyle.VerticalAlignment = VerticalAlignment.Center; sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(count, count, 0, data.Columns.Count - 1)); staticTimeCell.CellStyle = cellStyle; } else { IRow OrderRow = sheet.CreateRow(count); ICell OrderMakerCell = OrderRow.CreateCell(0); OrderMakerCell.SetCellValue(staticMode); ICell MakingTimeCell = OrderRow.CreateCell(data.Columns.Count - 2); MakingTimeCell.SetCellValue(staticTime); sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(count, count, 0, 1)); sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(count, count, data.Columns.Count - 2, data.Columns.Count - 1)); OrderMakerCell.CellStyle = cellLeftStyle; MakingTimeCell.CellStyle = cellRightStyle; } count++; } List _list = new List(); if (_title != null && _title.Count > 0) { int columns = -1; int cells = 0; IRow Rows = sheet.CreateRow(count); foreach (var item in _title) { columns += item.Value; ICell Cells = Rows.CreateCell(cells); Cells.SetCellValue(item.Key); sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(count, count, item.Value == 0 ? 0 : columns - (item.Value - 1), columns)); Cells.CellStyle = cellCenterStyle; cells += item.Value; for (int n = 0; n < item.Value; n++) { _list.Add(item.Key.Trim()); } } count++; } if (isColumnWritten == true) //写入DataTable的列名 { IRow row = sheet.CreateRow(count); for (j = 0; j < data.Columns.Count; ++j) { ICell Cells = row.CreateCell(j); if (_list != null && _list.Count > j && changeColumnName) { Cells.SetCellValue(data.Columns[j].ColumnName.Replace(_list[j], "")); } else { Cells.SetCellValue(data.Columns[j].ColumnName); } Cells.CellStyle = cellCenterStyle; } count++; } for (i = 0; i < data.Rows.Count; ++i) { IRow row = sheet.CreateRow(count); for (j = 0; j < data.Columns.Count; ++j) { ICell Cells = row.CreateCell(j); double _price; if (double.TryParse(data.Rows[i][j].ToString(), out _price) && (data.Columns[j].DataType == typeof(decimal) || data.Columns[j].DataType == typeof(int) || data.Columns[j].DataType == typeof(double))) { Cells.SetCellValue(_price); Cells.CellStyle = cellRightStyle; } else { string str_Data = Regex.Replace(Utils.ChangeHtmlToString( data.Rows[i][j].ToString()).Replace("", ""), @"]*>", ""); Cells.SetCellValue(str_Data); Cells.CellStyle = cellCenterStyle; } } ++count; } if (OrderMaker != "" && MakingTime != "") { IRow OrderRow = sheet.CreateRow(count); ICell OrderMakerCell = OrderRow.CreateCell(0); OrderMakerCell.SetCellValue(OrderMaker); ICell MakingTimeCell = OrderRow.CreateCell(data.Columns.Count - 2); MakingTimeCell.SetCellValue(MakingTime); sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(count, count, 0, 1)); sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(count, count, data.Columns.Count - 2, data.Columns.Count - 1)); OrderMakerCell.CellStyle = cellCenterStyle; MakingTimeCell.CellStyle = cellCenterStyle; count++; } #region 自动适应中文宽度 //获取当前列的宽度,然后对比本列的长度,取最大值 for (int columnNum = 0; columnNum <= data.Rows.Count; columnNum++) { int columnWidth = sheet.GetColumnWidth(columnNum) / 256; for (int rowNum = 1; rowNum <= sheet.LastRowNum; rowNum++) { IRow currentRow; //当前行未被使用过 if (sheet.GetRow(rowNum) == null) { currentRow = sheet.CreateRow(rowNum); } else { currentRow = sheet.GetRow(rowNum); } if (currentRow.GetCell(columnNum) != null) { ICell currentCell = currentRow.GetCell(columnNum); int length = Encoding.Default.GetBytes(currentCell.ToString()).Length; if (columnWidth < length) { columnWidth = length; } } } //sheet.SetColumnWidth(columnNum, columnWidth * 256); //列宽ColumnWidth的限制255个字符,以一个字符的1/256的宽度作为一个单位。 int colWidth = columnWidth * 256; if (colWidth < 255 * 256) { sheet.SetColumnWidth(columnNum, colWidth); } else { sheet.SetColumnWidth(columnNum, 6000); } } #endregion // 写入到客户端 System.IO.MemoryStream ms = new System.IO.MemoryStream(); workbook.Write(ms); //解决360浏览器导出Excel的文件名乱码 FileName = System.Web.HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8); HttpContext.Current.Response.Clear(); HttpContext.Current.Response.Buffer = true; HttpContext.Current.Response.Charset = "utf-8"; HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");//设置输出流为简体中文 HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format( "attachment; filename=" + FileName + "_{0}.xls", DateTime.Now.ToString("yyyyMMddHHmmssfff"))); HttpContext.Current.Response.BinaryWrite(ms.ToArray()); HttpContext.Current.Response.ContentType = "application/ms-excel";//设置输出文件类型为excel文件。 HttpContext.Current.Response.End(); workbook = null; ms.Close(); ms.Dispose(); return count; } catch (Exception ex) { ErrorLogHelper.Write(ex); return -1; } } /// /// 导出excel /// /// 标题 /// 统计方式(表单左上角) /// 统计时间(表单右上角) /// 制单人(表单左下角) /// 制单时间(表单右下角) /// 表头内容 /// 首列跨列数 /// 文件名称 /// 表单数据源 /// excel的表格名称 /// 表单表头是否显示为_title的内容 /// 表单表头是否去除重复内容, /// 如第一行显示“合计”,第二行显示“合计金额”,若changeColumnName为true则第二行显示为“金额” /// public int DataTableToExcelss(string Title, string staticMode, string staticTime, string OrderMaker, string MakingTime, string TitleText, int firstCloums, string FileName, DataTable data, string sheetName, bool isColumnWritten, bool changeColumnName = true) { int i = 0; int j = 0; int count = 0; ISheet sheet = null; if (fileName == null) { workbook = new NPOI.HSSF.UserModel.HSSFWorkbook(); } else { fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite); if (fileName.IndexOf(".xlsx") > 0) // 2007版本 workbook = new XSSFWorkbook(); else if (fileName.IndexOf(".xls") > 0) // 2003版本 workbook = new HSSFWorkbook(); } ICellStyle cellLeftStyle = workbook.CreateCellStyle(); cellLeftStyle.Alignment = HorizontalAlignment.Left; cellLeftStyle.VerticalAlignment = VerticalAlignment.Center; ICellStyle cellRightStyle = workbook.CreateCellStyle(); cellRightStyle.Alignment = HorizontalAlignment.Right; cellRightStyle.VerticalAlignment = VerticalAlignment.Center; ICellStyle cellCenterStyle = workbook.CreateCellStyle(); cellCenterStyle.Alignment = HorizontalAlignment.Center; cellCenterStyle.VerticalAlignment = VerticalAlignment.Center; try { if (workbook != null) { sheet = workbook.CreateSheet(sheetName); } else { return -1; } if (Title != "") { IRow titleRow = sheet.CreateRow(count); titleRow.Height = 1000; ICell titleCell = titleRow.CreateCell(0); titleCell.SetCellValue(Title.Replace("
", "\n").Replace("
", "\n").Replace("
", "\n")); ICellStyle cellStyle = workbook.CreateCellStyle(); IFont titleFont = workbook.CreateFont(); titleFont.Boldweight = (short)FontBoldWeight.Bold; titleFont.FontHeight = 18 * 18; cellStyle.SetFont(titleFont); cellStyle.Alignment = HorizontalAlignment.Center; cellStyle.VerticalAlignment = VerticalAlignment.Center; cellStyle.WrapText = true; sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(count, count, 0, data.Columns.Count - 1)); titleCell.CellStyle = cellStyle; count++; } if (!string.IsNullOrWhiteSpace(staticMode) || !string.IsNullOrWhiteSpace(staticTime)) { if (string.IsNullOrWhiteSpace(staticMode)) { IRow staticTimeRow = sheet.CreateRow(count); ICell staticTimeCell = staticTimeRow.CreateCell(0); staticTimeCell.SetCellValue(staticTime); ICellStyle cellStyle = workbook.CreateCellStyle(); cellStyle.Alignment = HorizontalAlignment.Right; cellStyle.VerticalAlignment = VerticalAlignment.Center; sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(count, count, 0, data.Columns.Count - 1)); staticTimeCell.CellStyle = cellStyle; } else if (string.IsNullOrWhiteSpace(staticTime)) { IRow staticTimeRow = sheet.CreateRow(count); ICell staticTimeCell = staticTimeRow.CreateCell(0); staticTimeCell.SetCellValue(staticMode); ICellStyle cellStyle = workbook.CreateCellStyle(); cellStyle.Alignment = HorizontalAlignment.Left; cellStyle.VerticalAlignment = VerticalAlignment.Center; sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(count, count, 0, data.Columns.Count - 1)); staticTimeCell.CellStyle = cellStyle; } else { IRow OrderRow = sheet.CreateRow(count); ICell OrderMakerCell = OrderRow.CreateCell(0); OrderMakerCell.SetCellValue(staticMode); ICell MakingTimeCell = OrderRow.CreateCell(data.Columns.Count - 2); MakingTimeCell.SetCellValue(staticTime); sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(count, count, 0, 1)); sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(count, count, data.Columns.Count - 2, data.Columns.Count - 1)); OrderMakerCell.CellStyle = cellLeftStyle; MakingTimeCell.CellStyle = cellRightStyle; } count++; } bool IsFirstColums = false; List _list = new List(); if (!string.IsNullOrEmpty(TitleText)) { foreach (string titleStr in TitleText.Split("")) { if (string.IsNullOrEmpty(titleStr)) { continue; } int columns = -1; int cells = 0; int ColumnsNum = 0; IRow Rows = sheet.CreateRow(count); if (!IsFirstColums) { string _text = titleStr.Split("<")[0]; columns += firstCloums; ICell Cells = Rows.CreateCell(cells); Cells.SetCellValue(_text); sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(count, count, (columns - (firstCloums - 1)), columns)); Cells.CellStyle = cellCenterStyle; cells += firstCloums; for (int n = 0; n < firstCloums; n++) { _list.Add(_text); } IsFirstColums = true; foreach (string columnsStr in titleStr.Split("")) { if (!string.IsNullOrEmpty(columnsStr)) { _text = columnsStr.Split(">")[1].Replace("", ""); int Colunms = columnsStr.Split("'")[1].TryParseToInt(); columns += Colunms; Cells = Rows.CreateCell(cells); Cells.SetCellValue(_text); sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(count, count, (columns - (Colunms - 1)), columns)); Cells.CellStyle = cellCenterStyle; cells += Colunms; for (int n = 0; n < Colunms; n++) { _list.Add(_text); } } } } else { foreach (string columnsStr in titleStr.Split("")) { if (!string.IsNullOrEmpty(columnsStr)) { string _text = columnsStr.Split(">")[1].Replace("", ""); int Colunms = columnsStr.Split("'")[1].TryParseToInt(); if (Colunms > 0) { columns += Colunms; ICell Cells = Rows.CreateCell(cells); Cells.SetCellValue(_text); sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(count, count, (columns - (Colunms - 1)), columns)); Cells.CellStyle = cellCenterStyle; cells += Colunms; for (int n = 0; n < Colunms; n++) { _list[ColumnsNum] += _text; ColumnsNum++; } } else { break; } } } } count++; } } count--; if (isColumnWritten == true) //写入DataTable的列名 { IRow row = sheet.CreateRow(count); for (j = 0; j < data.Columns.Count; ++j) { ICell Cells = row.CreateCell(j); if (_list != null && _list.Count > j && changeColumnName) { Cells.SetCellValue(data.Columns[j].ColumnName.Replace(_list[j], "")); } else { Cells.SetCellValue(data.Columns[j].ColumnName); } Cells.CellStyle = cellCenterStyle; } count++; } for (i = 0; i < data.Rows.Count; ++i) { IRow row = sheet.CreateRow(count); for (j = 0; j < data.Columns.Count; ++j) { ICell Cells = row.CreateCell(j); double _price; if (double.TryParse(data.Rows[i][j].ToString(), out _price) && (data.Columns[j].DataType == typeof(decimal) || data.Columns[j].DataType == typeof(int) || data.Columns[j].DataType == typeof(double))) { Cells.SetCellValue(_price); Cells.CellStyle = cellRightStyle; } else { string str_Data = Regex.Replace(Utils.ChangeHtmlToString( data.Rows[i][j].ToString()).Replace("", ""), @"]*>", ""); Cells.SetCellValue(str_Data); Cells.CellStyle = cellCenterStyle; } } ++count; } if (OrderMaker != "" && MakingTime != "") { IRow OrderRow = sheet.CreateRow(count); ICell OrderMakerCell = OrderRow.CreateCell(0); OrderMakerCell.SetCellValue(OrderMaker); ICell MakingTimeCell = OrderRow.CreateCell(data.Columns.Count - 2); MakingTimeCell.SetCellValue(MakingTime); sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(count, count, 0, 1)); sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(count, count, data.Columns.Count - 2, data.Columns.Count - 1)); OrderMakerCell.CellStyle = cellCenterStyle; MakingTimeCell.CellStyle = cellCenterStyle; count++; } #region 自动适应中文宽度 //获取当前列的宽度,然后对比本列的长度,取最大值 for (int columnNum = 0; columnNum <= data.Rows.Count; columnNum++) { int columnWidth = sheet.GetColumnWidth(columnNum) / 256; for (int rowNum = 1; rowNum <= sheet.LastRowNum; rowNum++) { IRow currentRow; //当前行未被使用过 if (sheet.GetRow(rowNum) == null) { currentRow = sheet.CreateRow(rowNum); } else { currentRow = sheet.GetRow(rowNum); } if (currentRow.GetCell(columnNum) != null) { ICell currentCell = currentRow.GetCell(columnNum); int length = Encoding.Default.GetBytes(currentCell.ToString()).Length; if (columnWidth < length) { columnWidth = length; } } } //sheet.SetColumnWidth(columnNum, columnWidth * 256); //列宽ColumnWidth的限制255个字符,以一个字符的1/256的宽度作为一个单位。 int colWidth = columnWidth * 256; if (colWidth < 255 * 256) { sheet.SetColumnWidth(columnNum, colWidth); } else { sheet.SetColumnWidth(columnNum, 6000); } } #endregion // 写入到客户端 System.IO.MemoryStream ms = new System.IO.MemoryStream(); workbook.Write(ms); //解决360浏览器导出Excel的文件名乱码 FileName = System.Web.HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8); HttpContext.Current.Response.Clear(); HttpContext.Current.Response.Buffer = true; HttpContext.Current.Response.Charset = "utf-8"; HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");//设置输出流为简体中文 HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format( "attachment; filename=" + FileName + "_{0}.xls", DateTime.Now.ToString("yyyyMMddHHmmssfff"))); HttpContext.Current.Response.BinaryWrite(ms.ToArray()); HttpContext.Current.Response.ContentType = "application/ms-excel";//设置输出文件类型为excel文件。 HttpContext.Current.Response.End(); workbook = null; ms.Close(); ms.Dispose(); return count; } catch (Exception ex) { ErrorLogHelper.Write(ex); return -1; } } #endregion #region 方法 -> 获取标题行 /// /// 获取标题行 /// /// public Dictionary GetTitleRows(int firstRowColumnspan, string HeardText, int rowsColumns = 0) { Dictionary _title = new Dictionary(); int columnspan = firstRowColumnspan; string _text = HeardText.Split("")[0].Replace("", ">"); _title.Add(_text.Split("<")[0], columnspan); string[] _str = _text.Split(">"); for (int i = 0; i < _str.Length; i++) { if ((i + 1) % 2 == 0) { _title.Add(_str[i], rowsColumns == 0 ? (columnspan) : rowsColumns); } else { if (_str[i] != "") { int.TryParse(_str[i].Split("'")[1], out columnspan); } } } return _title; } /// /// 获取标题行 /// /// public Dictionary GetTitleRowsNew(int firstRowColumnspan, string HeardText, int rowsColumns = 0, int col = 0) { Dictionary _title = new Dictionary(); int columnspan = firstRowColumnspan; string[] _strText = HeardText.Split(""); if (col > 0) { _title.Add("", col); } for (int i = 0; i < _strText.Length - 1; i++) { if (_strText[i] != "" && i == 1) { MatchCollection matches = Regex.Matches(_strText[i], "(?[^<]*?)", RegexOptions.IgnoreCase); if (matches.Count > 0) { for (int j = 0; j < matches.Count; j++) { _title.Add(matches[j].Groups["val2"].Value, Convert.ToInt32(matches[j].Groups["val1"].Value)); } } } } return _title; } #endregion #region 方法 -> ??? public int DataTableToExcelForEhange(string FileName, DataTable data, string sheetName, bool isColumnWritten) { int i = 0; int j = 0; int count = 0; ISheet sheet = null; if (fileName == null) { workbook = new NPOI.HSSF.UserModel.HSSFWorkbook(); } else { fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite); if (fileName.IndexOf(".xlsx") > 0) // 2007版本 workbook = new XSSFWorkbook(); else if (fileName.IndexOf(".xls") > 0) // 2003版本 workbook = new HSSFWorkbook(); } try { if (workbook != null) { sheet = workbook.CreateSheet(sheetName); } else { return -1; } if (isColumnWritten == true) //写入DataTable的列名 { IRow row = sheet.CreateRow(0); for (j = 0; j < data.Columns.Count; ++j) { row.CreateCell(j).SetCellValue(data.Columns[j].ColumnName); } count = 1; } else { count = 0; } for (i = 0; i < data.Rows.Count; ++i) { IRow row = sheet.CreateRow(count); for (j = 0; j < data.Columns.Count; ++j) { try { row.CreateCell(j).SetCellValue(data.Rows[i][j].ToString().ToEncrypt()); } catch (Exception ex) { SuperMap.RealEstate.Utility.ErrorLogHelper.Write(ex); } } ++count; } // 写入到客户端 System.IO.MemoryStream ms = new System.IO.MemoryStream(); workbook.Write(ms); HttpContext.Current.Response.Clear(); HttpContext.Current.Response.Buffer = true; HttpContext.Current.Response.Charset = "utf-8"; HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");//设置输出流为简体中文 HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + FileName); HttpContext.Current.Response.BinaryWrite(ms.ToArray()); HttpContext.Current.Response.ContentType = "application/ms-excel";//设置输出文件类型为excel文件。 HttpContext.Current.Response.End(); workbook = null; ms.Close(); ms.Dispose(); return count; } catch (Exception ex) { Console.WriteLine("Exception: " + ex.Message); return -1; } } #endregion #region 方法 -> 导入excel public static DataTable ExcelImport(string filePath) { NPOI.SS.UserModel.IWorkbook book = null; HSSFWorkbook hssfworkbook; #region //初始化信息 try { using (FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read)) { try { book = new NPOI.XSSF.UserModel.XSSFWorkbook(file); } catch (Exception ex) { book = new HSSFWorkbook(file); } } } catch (Exception e) { throw e; } #endregion NPOI.SS.UserModel.ISheet sheet = book.GetSheetAt(0); System.Collections.IEnumerator rows = sheet.GetRowEnumerator(); DataTable dt = new DataTable(); for (int j = 0; j < (sheet.GetRow(0).LastCellNum); j++) { dt.Columns.Add(Convert.ToChar(((int)'A') + j).ToString()); } while (rows.MoveNext()) { Type _Type = rows.Current.GetType(); IRow row = (IRow)rows.Current; //HSSFRow row = (HSSFRow) DataRow dr = dt.NewRow(); for (int i = 0; i < row.LastCellNum; i++) { NPOI.SS.UserModel.ICell cell = row.GetCell(i); if (cell == null) { dr[i] = null; } else { dr[i] = cell.ToString(); } } dt.Rows.Add(dr); } return dt; } #endregion #region 方法 -> 导出应收账款excel public int DataTableToExcels(string FileName, DataTable data, string sheetName, bool isColumnWritten, bool isDetail) { int i = 0; int j = 0; int count = 0; ISheet sheet = null; if (fileName == null) { workbook = new NPOI.HSSF.UserModel.HSSFWorkbook(); //NPOI.SS.UserModel.ISheet sheet = book.CreateSheet("Sheet1"); } else { fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite); if (fileName.IndexOf(".xlsx") > 0) // 2007版本 workbook = new XSSFWorkbook(); else if (fileName.IndexOf(".xls") > 0) // 2003版本 workbook = new HSSFWorkbook(); } try { if (workbook != null) { sheet = workbook.CreateSheet(sheetName); } else { return -1; } if (isColumnWritten == true) //写入DataTable的列名 { IRow row = sheet.CreateRow(0); if (!isDetail) { row.CreateCell(0).SetCellValue("服务区"); row.CreateCell(1).SetCellValue("所属区域"); row.CreateCell(2).SetCellValue("项目名称"); row.CreateCell(3).SetCellValue("经营商户"); row.CreateCell(4).SetCellValue("应收账款余额"); row.CreateCell(5).SetCellValue("账期<一个月"); row.CreateCell(6).SetCellValue("一个月<账期<三个月"); row.CreateCell(7).SetCellValue("三个月<账期"); row.CreateCell(8).SetCellValue("其他应收款余额"); row.CreateCell(9).SetCellValue("账期<一个月"); row.CreateCell(10).SetCellValue("一个月<账期<三个月"); row.CreateCell(11).SetCellValue("三个月<账期"); row.CreateCell(12).SetCellValue("逾期金额合计"); row.CreateCell(13).SetCellValue("逾期原因分析"); row.CreateCell(14).SetCellValue("备注"); } else { row.CreateCell(0).SetCellValue("所属区域"); row.CreateCell(1).SetCellValue("服务区"); row.CreateCell(2).SetCellValue("应收账款合计"); row.CreateCell(3).SetCellValue("正常(账期<1个月)"); row.CreateCell(4).SetCellValue("异常(1个月<账期<3个月)"); row.CreateCell(5).SetCellValue("严重逾期(3个月<账期)"); row.CreateCell(6).SetCellValue("其他应收款余额"); row.CreateCell(7).SetCellValue("正常(账期<1个月)"); row.CreateCell(8).SetCellValue("异常(1个月<账期<3个月)"); row.CreateCell(9).SetCellValue("严重逾期(3个月<账期)"); } count = 1; } else { count = 0; } for (i = 0; i < data.Rows.Count; ++i) { IRow row = sheet.CreateRow(count); for (j = 0; j < data.Columns.Count; ++j) { row.CreateCell(j).SetCellValue(data.Rows[i][j].ToString()); } ++count; } // 写入到客户端 System.IO.MemoryStream ms = new System.IO.MemoryStream(); workbook.Write(ms); HttpContext.Current.Response.Clear(); HttpContext.Current.Response.Buffer = true; HttpContext.Current.Response.Charset = "utf-8"; HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");//设置输出流为简体中文 HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment; filename=" + FileName + "_{0}.xls", DateTime.Now.ToString("yyyyMMddHHmmssfff"))); HttpContext.Current.Response.BinaryWrite(ms.ToArray()); HttpContext.Current.Response.ContentType = "application/ms-excel";//设置输出文件类型为excel文件。 HttpContext.Current.Response.End(); workbook = null; ms.Close(); ms.Dispose(); return count; } catch (Exception ex) { Console.WriteLine("Exception: " + ex.Message); return -1; } } #endregion public void setCellStyleAlignmentCenter(HSSFCellStyle style) { style.VerticalAlignment = NPOI.SS.UserModel.VerticalAlignment.Center; style.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center; } public HSSFFont createFont(HSSFWorkbook hssfworkbook) { return (HSSFFont)hssfworkbook.CreateFont(); } public void setCellStyleBord(HSSFCellStyle style) { style.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin; style.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin; style.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin; style.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin; } #region 方法 -> 导出采购单导入模板 public void ExcelExport(string fileName, string sheetName, bool isFirstRowColumn) { try { fs = new FileStream(fileName, FileMode.Open, FileAccess.Read); if (fileName.IndexOf(".xlsx") > 0) // 2007版本 workbook = new XSSFWorkbook(fs); else if (fileName.IndexOf(".xls") > 0) // 2003版本 workbook = new HSSFWorkbook(fs); // 写入到客户端 System.IO.MemoryStream ms = new System.IO.MemoryStream(); workbook.Write(ms); string downloadName = "采购单导入模板.xls"; HttpContext.Current.Response.Clear(); HttpContext.Current.Response.Buffer = true; HttpContext.Current.Response.Charset = "gb2312"; HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");//设置输出流为简体中文 if (HttpContext.Current.Request.Browser.Browser == "IE") downloadName = HttpUtility.UrlPathEncode(downloadName); string headerValue = string.Format("attachment; filename=\"{0}\"", downloadName); HttpContext.Current.Response.AddHeader("Content-Disposition", headerValue); HttpContext.Current.Response.ContentType = "application/octet-stream";//设置输出文件类型为excel文件。 HttpContext.Current.Response.BinaryWrite(ms.ToArray()); HttpContext.Current.Response.End(); workbook = null; ms.Close(); ms.Dispose(); } catch (Exception ex) { throw ex; } } #endregion #region 方法 -> 导出excel到Datatable /// /// 导出excel到Datatable /// /// 文件名称 /// 表单名称 /// 首行单元格数 /// public DataTable ExcelToDataTable(string fileName, string sheetName, bool isFirstRowColumn) { ISheet sheet = null; DataTable data = new DataTable(); int startRow = 0; try { fs = new FileStream(fileName, FileMode.Open, FileAccess.Read); //if (fileName.IndexOf(".xlsx") > 0) // 2007版本 // workbook = new XSSFWorkbook(fs); //else if (fileName.IndexOf(".xls") > 0) // 2003版本 // workbook = new HSSFWorkbook(fs); try { workbook = new XSSFWorkbook(fs); } catch { workbook = new HSSFWorkbook(fs); } if (sheetName != null) { sheet = workbook.GetSheet(sheetName); if (sheet == null) //如果没有找到指定的sheetName对应的sheet,则尝试获取第一个sheet { sheet = workbook.GetSheetAt(0); } } else { sheet = workbook.GetSheetAt(0); } if (sheet != null) { IRow firstRow = sheet.GetRow(0); int cellCount = firstRow.LastCellNum; //一行最后一个cell的编号 即总的列数 if (isFirstRowColumn) { for (int i = firstRow.FirstCellNum; i < cellCount; ++i) { ICell cell = firstRow.GetCell(i); if (cell != null) { string cellValue = cell.StringCellValue; if (cellValue != null) { DataColumn column = new DataColumn(cellValue); data.Columns.Add(column); } } } startRow = sheet.FirstRowNum + 1; } else { startRow = sheet.FirstRowNum; } //最后一列的标号 int rowCount = sheet.LastRowNum; for (int i = startRow; i <= rowCount; ++i) { IRow row = sheet.GetRow(i); if (row == null) continue; //没有数据的行默认是null        DataRow dataRow = data.NewRow(); for (int j = row.FirstCellNum; j < cellCount; ++j) { if (row.GetCell(j) != null) //同理,没有数据的单元格都默认是null dataRow[j] = row.GetCell(j).ToString(); } data.Rows.Add(dataRow); } } return data; } catch (Exception ex) { throw ex; } } #endregion #region 方法 -> 将GridViewEx导出为Excel表格文件 /// /// 将GridViewEx导出为Excel表格文件 /// 注意:GridViewEx中的HeaderText必须设置,且不可重复 /// /// 导出的文件名称 /// 表格Sheet标签名称 /// 表格标题名称 /// 统计方式(表格左上角显示的文本) /// 统计时间(表格右上角显示的文本) /// 制单人(表格左下角显示的文本) /// 制单时间(表格右下角显示的文本) /// 需要导出为Excel文件的GridViewEx对象 public void GridViewToExcel(string fileName, string sheetName, string tableTitle, string staticMode, string staticTime, string orderMaker, string makingTime, GridViewEx gridViewEx) { GridViewToExcel(fileName, sheetName, tableTitle, staticMode, staticTime, orderMaker, makingTime, gridViewEx, true); } /// /// 将GridViewEx导出为Excel表格文件 /// 注意:GridViewEx中的HeaderText必须设置,且不可重复 /// /// 导出的文件名称 /// 表格Sheet标签名称 /// 表格标题名称 /// 统计方式(表格左上角显示的文本) /// 统计时间(表格右上角显示的文本) /// 制单人(表格左下角显示的文本) /// 制单时间(表格右下角显示的文本) /// 需要导出为Excel文件的GridViewEx对象 /// 是否显示第一列的序号 public void GridViewToExcel(string fileName, string sheetName, string tableTitle, string staticMode, string staticTime, string orderMaker, string makingTime, GridViewEx gridViewEx, bool ContainFirstColumn) { DataTable data_Excel = new DataTable(); //按照页面显示添加列到Excel for (int i = 0; i < gridViewEx.Columns.Count; i++) { if (i == 0 && !ContainFirstColumn) continue; //只添加显示的列 if (gridViewEx.Columns[i].Visible) { data_Excel.Columns.Add(gridViewEx.Columns[i].HeaderText); } } int num = 1; //将页面呈现的数据写入Excel数据行 foreach (GridViewRow gvr_Row in gridViewEx.Rows) { DataRow dr_ExcelRow = data_Excel.NewRow(); for (int i = 0; i < gvr_Row.Cells.Count; i++) { if (i == 0 && !ContainFirstColumn) continue; //只写入显示的数据列 if (gridViewEx.Columns[i].Visible) { if (gridViewEx.Columns[i].HeaderText == "序号") { //序号列手动设置 dr_ExcelRow[gridViewEx.Columns[i].HeaderText] = num + "."; } else if (gvr_Row.Cells[i].Visible && gridViewEx.Columns[i].HeaderText.Replace(" ", "") != "") { //将数据写入对应单元格 //若值被省略,则使用提示 if (gvr_Row.Cells[i].Text.Trim().EndsWith("...") && !string.IsNullOrWhiteSpace( gvr_Row.Cells[i].ToolTip.Trim().Replace(" ", ""))) { dr_ExcelRow[gridViewEx.Columns[i].HeaderText] = Utils.ChangeHtmlToString( gvr_Row.Cells[i].ToolTip.Trim().Replace(" ", "")); } else { dr_ExcelRow[gridViewEx.Columns[i].HeaderText] = Utils.ChangeHtmlToString( gvr_Row.Cells[i].Text.Trim().Replace(" ", "")); } } } } data_Excel.Rows.Add(dr_ExcelRow); num++; } if (gridViewEx.Rows.Count > 0) { DataRow dr_FooterRow = data_Excel.NewRow(); //添加合计行数据到Excel for (int i = 0; i < gridViewEx.FooterRow.Cells.Count; i++) { //只写入显示的数据列 if (gridViewEx.Columns[i].Visible && gridViewEx.Columns[i].HeaderText.Replace(" ", "") != "") { dr_FooterRow[gridViewEx.Columns[i].HeaderText] = Utils.ChangeHtmlToString( gridViewEx.FooterRow.Cells[i].Text.Trim().Replace(" ", "")); } } data_Excel.Rows.Add(dr_FooterRow); } //读取GridViewEx中的自定义标题行(暂未实现) Dictionary dic_TableTitle = GetTitleRowsNew( gridViewEx.HeaderRow.Cells[0].ColumnSpan, gridViewEx.HeaderRow.Cells[0].Text); //生成并导出Excel文件 DataTableToExcel(tableTitle, staticMode, staticTime, orderMaker, makingTime, dic_TableTitle, fileName, data_Excel, sheetName, true); } #endregion } }