一、简介
NPOI是一个开源的C#读写Excel、Word等微软OLE2组件文档的项目,可以在没有安装Office的情况下对Word或Excel文档进行导入导出操作。
二、相关引用
1.ICsharpcode.SharpZipLib.dll 对文件进行压缩、解压操作,支持Zip, GZip, BZip2 和Tar格式
2.NPOI.dll 微软Excel BIFF(Excel 97-2003, doc)格式读写库,基础类库
3.NPOI.OOXML.dll Excel 2007(xlsx)格式读写库,Word 2007(docx)格式读写库
4.NPOI.OpenXml4Net.dll OpenXml底层zip包读写库
5.NPOI.OpenXmlFormats.dll 微软Office OpenXml对象关系库
三、导入Excel实例
1.新建一个类,命名为ExcelHelper。
2.添加引用:using NPOI.HSSF.UserModel;(Excel 97-2003, doc)格式读写库
using NPOI.SS.UserModel;Excel公用接口及Excel公式计算引擎
using NPOI.XSSF.UserModel;Excel 2007(xlsx)格式读写库
3.添加ExcelToTable方法
/// <summary>
/// 读取Excel
/// </summary>
/// <param name="file">文件全路径</param>
/// <param name="sheetName">excel表sheet名称</param>
/// <returns>返回DaTaTable</returns>
public static DataTable ExcelToTable(string file, string sheetName = null)
{
DataTable dt = new DataTable();
try
{
using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read))//打开excel文件
{
IWorkbook workbook = null;
if (file.IndexOf(".xlsx") > 0) // 2007版本
workbook = new XSSFWorkbook(fs);
else if (file.IndexOf(".xls") > 0) // 2003版本
workbook = new HSSFWorkbook(fs);
ISheet sheet = null;
if (sheetName == null)
sheet = workbook.GetSheetAt(0);//根据座标读区sheet表,0表示第一个
else
sheet = workbook.GetSheet(sheetName);//根据sheet名称读取sheet表
//列名
IRow rowHead = sheet.GetRow(sheet.FirstRowNum);//sheet.FirstRowNum 第一个单元格的行号
for (int i = 0; i < rowHead.LastCellNum; i++)//rowHead.LastCellNum 最后一个单元格的列号
{
string fildName = rowHead.GetCell(i).StringCellValue;
dt.Columns.Add(fildName, typeof(String));
}
//数据
for (int i = sheet.FirstRowNum + 1; i <= sheet.LastRowNum; i++)//sheet.LastRowNum最后一个单元格的行号
{
IRow row = sheet.GetRow(i);
DataRow dr = dt.NewRow();
for (int j = row.FirstCellNum; j < row.LastCellNum; j++)
{
ICell cell = row.GetCell(j);
dr[j] = GetValueType(cell);
if (dr[j] == null)
{
break;
}
}
dt.Rows.Add(dr);
}
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
return dt;
}
4.添加GetValueType方法
/// <summary>
/// 获取单元格类型(xlsx)
/// </summary>
/// <param name="cell"></param>
/// <returns></returns>
private static object GetValueType(ICell cell)
{
try
{
//XSSFCell
if (cell == null)
{
return null;
}
switch (cell.CellType)
{
case NPOI.SS.UserModel.CellType.Blank: //BLANK:
return null;
case NPOI.SS.UserModel.CellType.Boolean: //BOOLEAN:
return cell.BooleanCellValue;
case NPOI.SS.UserModel.CellType.Numeric: //NUMERIC:
return cell.NumericCellValue;
case NPOI.SS.UserModel.CellType.String: //STRING:
return cell.StringCellValue;
case NPOI.SS.UserModel.CellType.Error: //ERROR:
return cell.ErrorCellValue;
case NPOI.SS.UserModel.CellType.Formula: //FORMULA:
default:
return "=" + cell.CellFormula;
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
四、导出Excel实例
1、添加Export方法
/// <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();
HSSFSheet sheet = workbook.CreateSheet("Sheet1");//创建一张sheet表
#region 生成的excel文件,右击文件 属性信息,可以去掉
{
DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
dsi.Company = "http://www.baidu.com/";
workbook.DocumentSummaryInformation = dsi;
SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
si.Author = ""; //填加xls文件作者信息
si.ApplicationName = "NPOI测试程序"; //填加xls文件创建程序信息
si.LastAuthor = ""; //填加xls文件最后保存者信息
si.Comments = "说明信息"; //填加xls文件作者信息
si.Title = "NPOI测试"; //填加xls文件标题信息
si.Subject = "NPOI测试Demo";//填加文件主题信息
si.CreateDateTime = DateTime.Now;
workbook.SummaryInformation = si;
}
#endregion
HSSFCellStyle dateStyle = workbook.CreateCellStyle();//设置单元格样式
HSSFDataFormat 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(936).GetBytes(item.ColumnName.ToString()).Length;
}
for (int i = 0; i < dtSource.Rows.Count; i++)
{
for (int j = 0; j < dtSource.Columns.Count; j++)
{
int intTemp = Encoding.GetEncoding(936).GetBytes(dtSource.Rows[i][j].ToString()).Length;
if (intTemp > arrColWidth[j])
{
arrColWidth[j] = intTemp;
}
}
}
int rowIndex = 0;
foreach (DataRow row in dtSource.Rows)
{
#region 新建表,填充表头,填充列头,样式
if (rowIndex == 65535 || rowIndex == 0)//excel表2003及之前最大行数65536,2007后最大1048576行
{
if (rowIndex != 0)
{
sheet = workbook.CreateSheet();//创建一张sheet表
}
#region 表头及样式
{
HSSFRow headerRow = sheet.CreateRow(0);//设置首行
headerRow.HeightInPoints = 25;//设置高
headerRow.CreateCell(0).SetCellValue(strHeaderText);//设置表头文本
HSSFCellStyle headStyle = workbook.CreateCellStyle();//设置单元格样式
// headStyle.Alignment = CellHorizontalAlignment.CENTER;
HSSFFont font = workbook.CreateFont();//设置字体
font.FontHeightInPoints = 20;//字体大小
font.Boldweight = 700;//字体加粗
headStyle.SetFont(font);//设置字体
headerRow.GetCell(0).CellStyle = headStyle;
sheet.AddMergedRegion(new Region(0, 0, 0, dtSource.Columns.Count - 1));//合并单元格
}
#endregion
#region 列头及样式
{
HSSFRow headerRow = sheet.CreateRow(1);
HSSFCellStyle headStyle = workbook.CreateCellStyle();
HSSFFont font = workbook.CreateFont();
font.FontHeightInPoints = 10;
font.Boldweight = 700;//字体加粗
headStyle.SetFont(font);
foreach (DataColumn column in dtSource.Columns)
{
headerRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);
headerRow.GetCell(column.Ordinal).CellStyle = headStyle;
//设置列宽
sheet.SetColumnWidth(column.Ordinal, (arrColWidth[column.Ordinal] + 1) * 256);
}
}
#endregion
rowIndex = 2;
}
#endregion
#region 填充内容
HSSFRow dataRow = sheet.CreateRow(rowIndex);
foreach (DataColumn column in dtSource.Columns)
{
HSSFCell 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 = 0;
int.TryParse(drValue, out intV);
newCell.SetCellValue(intV);
break;
case "System.Decimal"://浮点型
case "System.Double":
double doubV = 0;
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 = 0;
return ms;
}
}
2、添加ExportByWeb方法
/// <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());//调用上面的Export方法
curContext.Response.End();
}