2025-03-28 09:49:56 +08:00

419 lines
16 KiB
C#

using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Web;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System.Web.UI.WebControls;
using System.Text;
namespace HZQR.Common
{
public class ExcelHelper
{
private string fileName = null; //文件名
private IWorkbook workbook = null;
private FileStream fs = null;
private bool disposed;
public int DataTableToExcel(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();
//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(data.Rows[i][j].ToString());
}
++count;
}
//列宽自适应,只对英文和数字有效
for (int c = 0; c <= data.Rows.Count;c++)
{
sheet.AutoSizeColumn(c);
}
#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);
long fileSize = ms.Length;
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-Length", fileSize.ToString()); //加上设置大小下载下来的.xls文件打开时才没有错误
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;
}
}
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)
{
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", "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;
}
}
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;
}
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;
}
}
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;
}
}
}