通过NPOI操作Excel
最近在做的一个项目中需要生成Excel,通过学习使用NPOI实现了相关需求,写了一个简便操作的类,记录如下:
public class NPOIHelperForExcel
{
#region excel文件属性 //作者
public string Author { get; set; } //标题
public string Title { get; set; } //主题
public string Subject { get; set; } //标记
public string Keywords { get; set; } //创建程序信息
public string ApplicationName { get; set; } //最后一次保存者
public string LastAuthor { get; set; } //备注
public string Comments { get; set; } //创建内容的时间
public DateTime? CreateDateTime { get; set; } //最后一次打印的时间
public DateTime? LastPrinted { get; set; } //最后一次保存的时间
public DateTime? LastSaveDateTime { get; set; } //公司
public string Company { get; set; } //管理者
public string Manager { get; set; } //比例
public bool Scale { get; set; } #endregion #region 导出,将DataTable导出为Excel文件
/// <summary>
/// DataTable导出到Excel文件
/// </summary>
/// <param name="dtSource">源DataTable</param>
/// <param name="headerTextList">表头摘要信息</param>
/// <param name="strFileName">保存位置</param>
public void Export(DataTable dtSource, List<String> headerTextList, string strFileName)
{
using (MemoryStream ms = Export(dtSource, headerTextList))
{
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="dtSource">源DataTable</param>
/// <param name="headerTextList">表头摘要信息</param>
public MemoryStream Export(DataTable dtSource, List<String> headerTextList)
{
HSSFWorkbook workbook = new HSSFWorkbook();
ISheet sheet = workbook.CreateSheet("sheet1"); //设置Excel文件属性信息
SetFileProperty(workbook); HSSFCellStyle dateStyle = (HSSFCellStyle)workbook.CreateCellStyle();
HSSFDataFormat format = (HSSFDataFormat)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 表头及样式
for (int i = ; i < headerTextList.Count; i++)
{
HSSFRow headerRow = (HSSFRow)sheet.CreateRow(i);
headerRow.HeightInPoints = ;
headerRow.CreateCell().SetCellValue(headerTextList[i]); HSSFCellStyle headerStyle = (HSSFCellStyle)workbook.CreateCellStyle();
headerStyle.Alignment = HorizontalAlignment.Left;
HSSFFont font = (HSSFFont)workbook.CreateFont();
font.FontHeightInPoints = ;
//font.Boldweight = 700;
headerStyle.SetFont(font);
headerRow.GetCell().CellStyle = headerStyle;
sheet.AddMergedRegion(new CellRangeAddress(, , , dtSource.Columns.Count - ));
}
#endregion #region 列头及样式
{
HSSFRow headerRow = (HSSFRow)sheet.CreateRow(headerTextList.Count);
HSSFCellStyle headStyle = (HSSFCellStyle)workbook.CreateCellStyle();
headStyle.Alignment = HorizontalAlignment.Center;
HSSFFont font = (HSSFFont)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 = headerTextList.Count + ;
} #endregion #region 填充表格内容 HSSFRow dataRow = (HSSFRow)sheet.CreateRow(rowIndex);
foreach (DataColumn column in dtSource.Columns)
{
HSSFCell newCell = (HSSFCell)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 = ; return ms;
} } /// <summary>
/// 用于Web导出
/// </summary>
/// <param name="dtSource">源DataTable</param>
/// <param name="headerTextList">表头摘要信息</param>
/// <param name="strFileName">文件名</param>
public void ExportByWeb(DataTable dtSource, List<String> headerTextList, 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, headerTextList).GetBuffer());
curContext.Response.End();
}
#endregion #region 导入,将excel读取到DataTable中
/// <summary>
/// 读取excel,默认第一行为表头
/// </summary>
/// <param name="strFileName">excel文件路径</param>
/// <returns>DataTable</returns>
public DataTable Import(string strFileName)
{
return Import(strFileName, );
} /// <summary>
/// 读取excel
/// </summary>
/// <param name="strFileName">excel文件路径</param>
/// <param name="sheetNum">sheet索引,以0开始</param>
/// <returns>DataTable</returns>
public DataTable Import(string strFileName, int sheetNum)
{
return Import(strFileName, sheetNum, , );
} /// <summary>
/// 读取excel
/// </summary>
/// <param name="strFileName">excel文件路径</param>
/// <param name="sheetNum">sheet索引,以0开始</param>
/// <param name="startRowNum">起始行号,即:表头在Excel中的行号</param>
/// <param name="startColNum">起始列号</param>
/// <returns>DataTable</returns>
public DataTable Import(string strFileName, int sheetNum, int startRowNum, int startColNum)
{
return Import(strFileName, sheetNum, startRowNum, -, startColNum, -);
} /// <summary>
/// 读取excel
/// sheet.LastRowNum属性获取的是Excel中该工作表(sheet)的末行行号减1;
/// headerRow.LastCellNum属性获取的是Excel中该行的列数
/// </summary>
/// <param name="strFileName">excel文档路径</param>
/// <param name="sheetNum">工作表索引,以0开始</param>
/// <param name="startRowNum">起始行号,即:表头在Excel中的行号</param>
/// <param name="endRowNum">结束行号</param>
/// <param name="startColNum">起始列号</param>
/// <param name="endColNum">结束列号</param>
/// <returns>DataTable</returns>
public DataTable Import(string strFileName, int sheetNum, int startRowNum, int endRowNum, int startColNum, int endColNum)
{
DataTable dt = new DataTable(); HSSFWorkbook hssfworkbook;
using (FileStream file = new FileStream(strFileName, FileMode.Open, FileAccess.Read))
{
hssfworkbook = new HSSFWorkbook(file);
} int sheetCount = hssfworkbook.NumberOfSheets; sheetNum = sheetNum < || sheetNum > sheetCount - ? : sheetNum; HSSFSheet sheet = (HSSFSheet)hssfworkbook.GetSheetAt(sheetNum); HSSFRow headerRow = null; #region 行列号范围验证 startColNum = startColNum < ? : startColNum; startRowNum = startRowNum < ? : startRowNum; headerRow = (HSSFRow)sheet.GetRow(startRowNum - ); endColNum = (endColNum > headerRow.LastCellNum || endColNum < ) ? headerRow.LastCellNum : endColNum; endRowNum = (endRowNum - > sheet.LastRowNum || endRowNum < ) ? sheet.LastRowNum + : endColNum; #endregion //添加列
for (int j = startColNum - ; j < endColNum; j++)
{
HSSFCell cell = (HSSFCell)headerRow.GetCell(j);
dt.Columns.Add(cell.ToString());
} //添加行
for (int i = startRowNum; i <= endRowNum - ; i++)
{
HSSFRow row = (HSSFRow)sheet.GetRow(i);
DataRow dataRow = dt.NewRow(); for (int j = startColNum - ; j < endColNum; j++)
{
if (row.GetCell(j) != null)
dataRow[j - startColNum + ] = row.GetCell(j).ToString();
} dt.Rows.Add(dataRow);
}
return dt;
}
#endregion #region 单元格写入
///// <summary>
///// 给指定单元格写入内容
///// </summary>
///// <param name="workBook"></param>
///// <param name="sheetName"></param>
///// <param name="rowNum"></param>
///// <param name="colNum"></param>
///// <param name="content"></param>
//public void WriteCell(HSSFWorkbook workBook, string sheetName, int rowNum, int colNum, string content)
//{
// if (workBook == null)
// {
// throw new Exception("workBook不能为null");
// }
// WriteCell(workBook, workBook.GetSheetIndex(sheetName), rowNum, colNum, content);
//} ///// <summary>
///// 给指定单元格写入内容
///// </summary>
///// <param name="workBook"></param>
///// <param name="sheetNum"></param>
///// <param name="rowNum"></param>
///// <param name="colNum"></param>
///// <param name="content"></param>
///// <returns></returns>
//public void WriteCell(HSSFWorkbook workBook, int sheetNum, int rowNum, int colNum, string content)
//{
// if (workBook == null)
// {
// throw new Exception("workBook不能为null");
// } // if (workBook.NumberOfSheets < sheetNum || sheetNum < 0)
// {
// throw new Exception("指定的sheet不存在");
// } // ISheet sheet = workBook.GetSheetAt(sheetNum - 1); // HSSFRow row = (HSSFRow)sheet.GetRow(rowNum) ?? (HSSFRow)sheet.CreateRow(rowNum - 1);
// HSSFCell cell = (HSSFCell)row.CreateCell(6);
// cell.SetCellValue(content); // //using (MemoryStream ms = new MemoryStream())
// //{
// // workBook.Write(ms);
// // ms.Flush();
// // ms.Position = 0; // // using (FileStream fs = new FileStream("测试行列写入.xls", FileMode.Create, FileAccess.Write))
// // {
// // byte[] data = ms.ToArray();
// // fs.Write(data, 0, data.Length);
// // fs.Flush();
// // }
// //}
// //return workBook;
//}
#endregion /// <summary>
/// 设置Excel文件属性信息
/// </summary>
/// <param name="workbook"></param>
private void SetFileProperty(HSSFWorkbook workbook)
{
DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
dsi.Company = this.Company ?? "";
dsi.Scale = this.Scale;
dsi.Manager = this.Manager ?? "";
workbook.DocumentSummaryInformation = dsi;
SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
si.Author = this.Author ?? "";
si.ApplicationName = this.ApplicationName ?? "";
si.LastAuthor = this.LastAuthor ?? "";
si.Comments = this.Comments ?? "";
si.Title = this.Title ?? "";
si.Subject = this.Subject ?? "";
si.CreateDateTime = this.CreateDateTime ?? DateTime.Now;
si.Keywords = this.Keywords ?? "";
si.LastAuthor = this.LastAuthor ?? "";
si.LastPrinted = this.LastPrinted ?? DateTime.Now;
si.LastSaveDateTime = this.LastSaveDateTime ?? DateTime.Now;
//上面的属性必须赋值,不能为null,不然执行到Export方法的"workbook.Write(ms);"处会导致空引用错误。
workbook.SummaryInformation = si;
}
}
通过NPOI操作Excel的更多相关文章
- NPOI操作Excel辅助类
/// <summary> /// NPOI操作excel辅助类 /// </summary> public static class NPOIHelper { #region ...
- NPOI操作excel之写入数据到excel表
在上一篇<NPOI操作excel之读取excel数据>我们把excel数据写入了datatable中,本篇就讲如何把datatable数据写入excel中. using System; u ...
- C#开发中使用Npoi操作excel实例代码
C#开发中使用Npoi操作excel实例代码 出处:西西整理 作者:西西 日期:2012/11/16 9:35:50 [大 中 小] 评论: 0 | 我要发表看法 Npoi 是什么? 1.整个Exce ...
- 用NPOI操作EXCEL关于HSSFClientAnchor(dx1,dy1,dx2,dy2,col1,row1,col2,row2)的参数
2.4.1 用NPOI操作EXCEL关于HSSFClientAnchor(dx1,dy1,dx2,dy2,col1,row1,col2,row2)的参数 NPOI教程:http://www.cnb ...
- C# 如何使用NPOI操作Excel以及读取合并单元格等
C#操作Excel方法有很多,以前用的需要电脑安装office才能用,但因为版权问题公司不允许安装office.所以改用NPOI进行Excel操作,基本上一些简单的Excel操作都没有问题,读写合并单 ...
- 用NPOI操作EXCEL-锁定列CreateFreezePane()
public void ExportPermissionRoleData(string search, int roleStatus) { var workbook = new HSSFWorkboo ...
- .NET 通过 NPOI 操作 Excel
目录 .NET 通过 NPOI 操作 Excel 第一步:通过 NuGet 获取 NPOI 包并引入程序集 第二步:引入 NPOI 帮助类 第三步:在程序中调用相应的方法对数据进行导出导入操作 将 D ...
- 2.6.2 用NPOI操作EXCEL--设置密码才可以修改单元格内容
2.6.2 用NPOI操作EXCEL--设置密码 有时,我们可能需要某些单元格只读,如在做模板时,模板中的数据是不能随意让别人改的.在Excel中,可以通过“审阅->保护工作表”来完 ...
- 使用NPOI操作Excel文件及其日期处理
工作中经常遇到需要读取或导出Excel文件的情况,而NPOI是目前最宜用.效率最高的操作的Office(不只是Excel哟)文件的组件,使用方便,不详细说明了. Excel工作表约定:整个Excel表 ...
- C#通过NPOI操作Excel
参考页面: http://www.yuanjiaocheng.net/webapi/create-crud-api-1-post.html http://www.yuanjiaocheng.net/w ...
随机推荐
- static,你还敢用吗?(二)
为了压系统,昨天小组在测试环境模拟了一大批订单数据.今天上午查看记录的账单计息日志,发现了一大堆的MySqlException MySql.Data.MySqlClient.MySqlExceptio ...
- 【开源】简单4步搞定QQ登录,无需什么代码功底【无语言界限】
说17号发超简单的教程就17号,qq核审通过后就封装了这个,现在放出来~~ 这个是我封装的一个开源项目:https://github.com/dunitian/LoTQQLogin ————————— ...
- Laravel Composer and ServiceProvider
Composer and: 创建自定义类库时,按命名空间把文件夹结构组织好 composer.json>autoload>classmap>psr-4 composer dump-a ...
- [C#] 简单的 Helper 封装 -- RegularExpressionHelper
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.T ...
- pt-ioprofile
pt-ioprofile是用来观察特定进程的IO信息的. 该脚本是用shell写的,有两方面的作用: pt-ioprofile does two things: ) ) is not performe ...
- 简记用ArcGIS处理某项目需求中数据的步骤
文章版权由作者李晓晖和博客园共有,若转载请于明显处标明出处:http://www.cnblogs.com/naaoveGIS/ 1. 背景 项目需求涉及如下几个步骤: a.矢量化 b.获取范围内要素 ...
- js面向对象学习 - 对象概念及创建对象
原文地址:js面向对象学习笔记 一.对象概念 对象是什么?对象是“无序属性的集合,其属性可以包括基本值,对象或者函数”.也就是一组名值对的无序集合. 对象的特性(不可直接访问),也就是属性包含两种,数 ...
- Android Studio开发RecyclerView遇到的各种问题以及解决(一)
以前一直在用ListView,,,最近才看RecyclerView发现好强大.RecyclerView前提是Android版本在5.0以上,本人以前用的是eclipse只支持到4.4.索性就安装一个A ...
- linux基础命令
系统信息 arch 显示机器的处理器架构(1) uname -m 显示机器的处理器架构(2) uname -r 显示正在使用的内核版本 dmidecode -q 显示硬件系统部件 - (SMBIOS ...
- BZOJ 3110: [Zjoi2013]K大数查询 [树套树]
3110: [Zjoi2013]K大数查询 Time Limit: 20 Sec Memory Limit: 512 MBSubmit: 6050 Solved: 2007[Submit][Sta ...