public class NPOIHelper
{
/// <summary>
/// DataTable导出到Excel文件
/// </summary>
/// <param name="dtSource">源DataTable</param>
/// <param name="strHeaderText">表头文本</param>
/// <param name="strFileName">保存位置</param>
public static void ExportByServer(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, , data.Length);
fs.Flush();
}
}
} /// <summary>
/// 用于Web导出
/// </summary>
/// <param name="dtSource">源DataTable</param>
/// <param name="strHeaderText">表头文本</param>
/// <param name="strFileName">文件名</param>
public static void ExportByWeb(DataTable 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(Export(dtSource, strHeaderText).GetBuffer());
curContext.Response.End();
} /// <summary>读取excel
/// 默认第一行为标头
/// </summary>
/// <param name="strFileName">excel文档路径</param>
/// <returns></returns>
public static DataTable Import(string strFileName)
{
DataTable dt = new DataTable(); HSSFWorkbook hssfworkbook;
using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read))
{
hssfworkbook = new HSSFWorkbook(file);
}
ISheet sheet = hssfworkbook.GetSheetAt();
System.Collections.IEnumerator rows = sheet.GetRowEnumerator(); IRow headerRow = sheet.GetRow();
int cellCount = headerRow.LastCellNum; for (int j = ; j < cellCount; j++)
{
ICell cell = headerRow.GetCell(j);
dt.Columns.Add(cell.ToString());
} for (int i = (sheet.FirstRowNum + ); 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的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 = "Sohu";
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;
}
#endregion ICellStyle dateStyle = workbook.CreateCellStyle();
IDataFormat format = workbook.CreateDataFormat();
dateStyle.DataFormat = format.GetFormat("yyyy-mm-dd"); //取得列宽
int[] arrColWidth = new int[dtSource.Columns.Count];
foreach (DataColumn item in dtSource.Columns)
{
arrColWidth[item.Ordinal] = Encoding.GetEncoding().GetBytes(item.ColumnName.ToString()).Length;
}
for (int i = ; i < dtSource.Rows.Count; i++)
{
for (int j = ; j < dtSource.Columns.Count; j++)
{
int intTemp = Encoding.GetEncoding().GetBytes(dtSource.Rows[i][j].ToString()).Length;
if (intTemp > arrColWidth[j])
{
arrColWidth[j] = intTemp;
}
}
}
int rowIndex = ;
foreach (DataRow row in dtSource.Rows)
{
#region 新建表,填充表头,填充列头,样式
if (rowIndex == || rowIndex == )
{
if (rowIndex != )
{
sheet = workbook.CreateSheet();
} #region 表头及样式
{
IRow headerRow = sheet.CreateRow();
headerRow.HeightInPoints = ;
headerRow.CreateCell().SetCellValue(strHeaderText); ICellStyle headStyle = workbook.CreateCellStyle();
headStyle.Alignment = HorizontalAlignment.Center;
IFont font = workbook.CreateFont();
font.FontHeightInPoints = ;
font.Boldweight = ;
headStyle.SetFont(font);
headerRow.GetCell().CellStyle = headStyle;
sheet.AddMergedRegion(new CellRangeAddress(, , , dtSource.Columns.Count - )); }
#endregion #region 列头及样式
{
IRow headerRow = sheet.CreateRow(); ICellStyle headStyle = workbook.CreateCellStyle();
headStyle.Alignment = HorizontalAlignment.Center; IFont font = workbook.CreateFont();
font.FontHeightInPoints = ;
font.Boldweight = ;
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] + ) * );
} }
#endregion rowIndex = ;
}
#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);
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);
break;
case "System.Int16"://整型
case "System.Int32":
case "System.Int64":
case "System.Byte":
int intV = ;
int.TryParse(drValue, out intV);
newCell.SetCellValue(intV);
break;
case "System.Decimal"://浮点型
case "System.Double":
double doubV = ;
double.TryParse(drValue, out doubV);
newCell.SetCellValue(doubV);
break;
case "System.DBNull"://空值处理
newCell.SetCellValue("");
break;
default:
newCell.SetCellValue("");
break;
} }
#endregion rowIndex++;
}
using (MemoryStream ms = new MemoryStream())
{
workbook.Write(ms);
ms.Flush();
ms.Position = ; //sheet.Dispose();
//workbook.Dispose();//一般只用写这一个就OK了,他会遍历并释放所有资源,但当前版本有问题所以只释放sheet
return ms;
}
} /// <summary>
/// DataTable按模板导出到Excel文件
/// </summary>
/// <param name="dtSource">源DataTable</param>
/// <param name="TempletFileName">模板文件</param>
/// <param name="strFileName">保存位置</param>
public static void ExportByTemplate(string TempletFileName, string strFileName, DataTable dt, string Type)
{
using (MemoryStream ms = ExportByTemp(TempletFileName, dt, Type))
{
using (FileStream fs = new FileStream(strFileName, FileMode.Create, FileAccess.Write))
{
byte[] data = ms.ToArray();
fs.Write(data, , data.Length);
fs.Flush();
}
}
}
/// <summary>
/// DataTable导出到Excel的MemoryStream
/// </summary>
/// <param name="dt">数据源</param>
/// <param name="TempletFileName">Excel模板</param>
/// <returns></returns>
public static MemoryStream ExportByTemp(string TempletFileName, DataTable dt,string Type)
{
FileStream file = new FileStream(TempletFileName, FileMode.Open, FileAccess.Read); HSSFWorkbook workbook = new HSSFWorkbook(file);
ISheet sheet = workbook.GetSheetAt(); //ICellStyle dateStyle = workbook.CreateCellStyle();
//dateStyle.BorderBottom = BorderStyle.Thin;
//dateStyle.BorderLeft = BorderStyle.Thin;
//dateStyle.BorderRight = BorderStyle.Thin;
//dateStyle.BorderTop = BorderStyle.Thin; int rowIndex = ; foreach (DataRow entity in dt.Rows)
{
IRow dataRow = sheet.CreateRow(rowIndex); if (Type.Equals("SaleType"))
{
ICell newCell0 = dataRow.CreateCell();
newCell0.SetCellValue(entity[].ToString());
//newCell0.CellStyle = dateStyle;
}
else {
ICell newCell0 = dataRow.CreateCell();
newCell0.SetCellValue(entity[].ToString());
//newCell0.CellStyle = dateStyle;
}
//ICell newCell7 = dataRow.CreateCell(7);
//if (type.Equals("excel"))
//{
// newCell7.SetCellValue(entity.Location == "" ? "" : "第" + entity.Location + "行");
//}
//else if (type.Equals("word"))
//{
// newCell7.SetCellValue(entity.Location == "" ? "" : "第" + entity.Location + "页");
//}
//newCell7.CellStyle = dateStyle; rowIndex++;
}
if (dt.Rows.Count == )
{
IRow dataRow = sheet.CreateRow(rowIndex);
ICell newCelllast = dataRow.CreateCell();
newCelllast.SetCellValue(" ");
} using (MemoryStream ms = new MemoryStream())
{
workbook.Write(ms);
ms.Flush();
ms.Position = ; //sheet.Dispose();
//workbook.Dispose();//一般只用写这一个就OK了,他会遍历并释放所有资源,但当前版本有问题所以只释放sheet
return ms;
}
} public static void ExportByNodeData(string TfileName, string StrfileName, DataTable dt, string Type,double Rate)
{
using (MemoryStream ms = ExportByNode(TfileName, dt, Type,Rate))
{
using (FileStream fs = new FileStream(StrfileName, FileMode.Create, FileAccess.Write))
{
byte[] data = ms.ToArray();
fs.Write(data, , data.Length);
fs.Flush();
}
}
}
public static MemoryStream ExportByNode(string TempletFileName, DataTable dt, string Type, double Rate)
{
FileStream file = new FileStream(TempletFileName, FileMode.Open, FileAccess.Read); HSSFWorkbook workbook = new HSSFWorkbook(file);
ISheet sheet = workbook.GetSheetAt(); ICellStyle dateStyle = workbook.CreateCellStyle();
dateStyle.BorderBottom = BorderStyle.Thin;
dateStyle.BorderLeft = BorderStyle.Thin;
dateStyle.BorderRight = BorderStyle.Thin;
dateStyle.BorderTop = BorderStyle.Thin; int rowIndex = ; foreach (DataRow entity in dt.Rows)
{
IRow dataRow = sheet.CreateRow(rowIndex); if (Type.Equals("SaleTypeExport"))
{
ICell newCell0 = dataRow.CreateCell();
newCell0.SetCellValue(rowIndex);
newCell0.CellStyle = dateStyle; ICell newCell1 = dataRow.CreateCell();
newCell1.SetCellValue(entity["new_nodename"].ToString());
newCell1.CellStyle = dateStyle; ICell newCell2 = dataRow.CreateCell();
newCell2.SetCellValue(Convert.ToDouble(entity["new_lastyear_total"].ToString()));
newCell2.CellStyle = dateStyle; ICell newCell3 = dataRow.CreateCell();
newCell3.SetCellValue(Convert.ToDouble(entity["new_total_assign2me"].ToString()));
newCell3.CellStyle = dateStyle; ICell newCell4 = dataRow.CreateCell();
newCell4.SetCellValue(Convert.ToInt32(entity["new_accountadd"].ToString()));
newCell4.CellStyle = dateStyle; ICell newCell5 = dataRow.CreateCell();
newCell5.SetCellValue(Convert.ToDouble(entity["new_total_assign2me"].ToString()) - (Convert.ToDouble(entity["new_total_assign2me"].ToString()) * Rate));
newCell5.CellStyle = dateStyle; ICell newCell6 = dataRow.CreateCell();
newCell6.SetCellValue((Convert.ToDouble(entity["new_total_assign2me"].ToString()) * Rate));
newCell6.CellStyle = dateStyle; ICell newCell7 = dataRow.CreateCell();
newCell7.SetCellValue(Convert.ToDouble(entity["RefeAmount"].ToString()));
newCell7.CellStyle = dateStyle; ICell newCell8 = dataRow.CreateCell();
newCell8.SetCellValue(entity["new_description"].ToString());
newCell8.CellStyle = dateStyle;
}
else if (Type.Equals("AccountTypeExport"))
{
ICell newCell0 = dataRow.CreateCell();
newCell0.SetCellValue(rowIndex);
newCell0.CellStyle = dateStyle; ICell newCell1 = dataRow.CreateCell();
newCell1.SetCellValue(entity["new_name"].ToString());
newCell1.CellStyle = dateStyle; ICell newCell2 = dataRow.CreateCell();
newCell2.SetCellValue(Convert.ToDouble(entity["new_lastyear_total"].ToString()));
newCell2.CellStyle = dateStyle; ICell newCell3 = dataRow.CreateCell();
newCell3.SetCellValue(Convert.ToDouble(entity["new_nodetemdesc_amount"].ToString()));
newCell3.CellStyle = dateStyle; ICell newCell4 = dataRow.CreateCell();
newCell4.SetCellValue(Convert.ToDouble(entity["new_nodetemdesc_amount"].ToString()) - (Convert.ToDouble(entity["new_nodetemdesc_amount"].ToString()) * Rate));
newCell4.CellStyle = dateStyle; ICell newCell5 = dataRow.CreateCell();
newCell5.SetCellValue((Convert.ToDouble(entity["new_nodetemdesc_amount"].ToString()) * Rate));
newCell5.CellStyle = dateStyle; ICell newCell6 = dataRow.CreateCell();
newCell6.SetCellValue(Convert.ToDouble(entity["RefeAmount"].ToString()));
newCell6.CellStyle = dateStyle; ICell newCell7 = dataRow.CreateCell();
newCell7.SetCellValue(entity["new_nodetemdesc_description"].ToString());
newCell7.CellStyle = dateStyle;
}
else if (Type.Equals("NodeDescByAccountExport"))
{
ICell newCell0 = dataRow.CreateCell();
newCell0.SetCellValue(rowIndex);
newCell0.CellStyle = dateStyle; ICell newCell1 = dataRow.CreateCell();
newCell1.SetCellValue(entity["new_name"].ToString());
newCell1.CellStyle = dateStyle; ICell newCell2 = dataRow.CreateCell();
newCell2.SetCellValue(Convert.ToDouble(entity["new_nodetemdesc_amount"].ToString()));
newCell2.CellStyle = dateStyle; ICell newCell3 = dataRow.CreateCell();
newCell3.SetCellValue(Convert.ToDouble(entity["new_nodetemdesc_amount"].ToString()) - (Convert.ToDouble(entity["new_nodetemdesc_amount"].ToString()) * Rate));
newCell3.CellStyle = dateStyle; ICell newCell4 = dataRow.CreateCell();
newCell4.SetCellValue((Convert.ToDouble(entity["new_nodetemdesc_amount"].ToString()) * Rate));
newCell4.CellStyle = dateStyle; ICell newCell5 = dataRow.CreateCell();
newCell5.SetCellValue(Convert.ToDouble(entity["RefeAmount"].ToString()));
newCell5.CellStyle = dateStyle; ICell newCell6 = dataRow.CreateCell();
newCell6.SetCellValue(entity["new_nodetemdesc_description"].ToString());
newCell6.CellStyle = dateStyle;
}
else if (Type.Equals("NodeDescBySaleExport"))
{
ICell newCell0 = dataRow.CreateCell();
newCell0.SetCellValue(rowIndex);
newCell0.CellStyle = dateStyle; ICell newCell1 = dataRow.CreateCell();
newCell1.SetCellValue(entity["new_name"].ToString());
newCell1.CellStyle = dateStyle; ICell newCell2 = dataRow.CreateCell();
newCell2.SetCellValue(Convert.ToDouble(entity["new_distributeamount"].ToString()));
newCell2.CellStyle = dateStyle; ICell newCell3 = dataRow.CreateCell();
newCell3.SetCellValue(Convert.ToDouble(entity["new_distributeamount"].ToString()) - (Convert.ToDouble(entity["new_distributeamount"].ToString()) * Rate));
newCell3.CellStyle = dateStyle; ICell newCell4 = dataRow.CreateCell();
newCell4.SetCellValue((Convert.ToDouble(entity["new_distributeamount"].ToString()) * Rate));
newCell4.CellStyle = dateStyle; ICell newCell5 = dataRow.CreateCell();
newCell5.SetCellValue(Convert.ToDouble(entity["RefeAmount"].ToString()));
newCell5.CellStyle = dateStyle; ICell newCell6 = dataRow.CreateCell();
newCell6.SetCellValue(entity["new_description"].ToString());
newCell6.CellStyle = dateStyle;
}
rowIndex++;
} using (MemoryStream ms = new MemoryStream())
{
workbook.Write(ms);
ms.Flush();
ms.Position = ; //sheet.Dispose();
//workbook.Dispose();//一般只用写这一个就OK了,他会遍历并释放所有资源,但当前版本有问题所以只释放sheet
return ms;
}
} }