npoi导入导出

NPOI是指构建在POI 3.x版本之上的一个程序,NPOI可以在没有安装Office的情况下对Word或Excel文档进行读写操作。
NPOI是一个开源的Java读写Excel、WORD等微软OLE2组件文档的项目。
同时支持文件的导入和导出,

先去官网:http://npoi.codeplex.com/下载需要引入dll(可以选择.net2.0或者.net4.0的dll),然后在网站中添加引用。

Asp.Net导入代码:

HSSFWorkbook hssfworkbook;
XSSFWorkbook wb;
/// <summary>
/// Asp.Net导入代码
/// </summary>
/// <param name=”filePath”></param>
/// <returns></returns>
public DataTable ImportExcelFile(string filePath)
{
#region//初始化信息
try
{
using (FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
//hssfworkbook = new HSSFWorkbook(file);
wb = new XSSFWorkbook(file);
}
}
catch (Exception e)
{
throw e;
}
#endregion

//NPOI.SS.UserModel.ISheet sheet = hssfworkbook.GetSheetAt(0);
NPOI.SS.UserModel.ISheet sheet = wb.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())
{
//HSSFRow row = (HSSFRow)rows.Current;
XSSFRow row = (XSSFRow)rows.Current;
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;
}

Asp.Net导出代码:

/// <summary>
/// C#导出Excel
/// </summary>
/// <param name=”dt”></param>
/// <param name=”filePath”></param>
public static void WriteExcel(DataTable dt, string filePath)
{
if (!string.IsNullOrEmpty(filePath) && null != dt && dt.Rows.Count > 0)
{
NPOI.HSSF.UserModel.HSSFWorkbook book = new NPOI.HSSF.UserModel.HSSFWorkbook();
NPOI.SS.UserModel.ISheet sheet = book.CreateSheet(dt.TableName);

NPOI.SS.UserModel.IRow row = sheet.CreateRow(0);
for (int i = 0; i < dt.Columns.Count; i++)
{
row.CreateCell(i).SetCellValue(dt.Columns[i].ColumnName);
}
for (int i = 0; i < dt.Rows.Count; i++)
{
NPOI.SS.UserModel.IRow row2 = sheet.CreateRow(i + 1);
for (int j = 0; j < dt.Columns.Count; j++)
{
row2.CreateCell(j).SetCellValue(Convert.ToString(dt.Rows[i][j]));
}
}
// 写入到客户端
using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
{
book.Write(ms);
using (FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write))
{
byte[] data = ms.ToArray();
fs.Write(data, 0, data.Length);
fs.Flush();
}
book = null;
}
}

posted on 2017-11-28 21:18 唯优 阅读() 评论() 编辑 收藏

版权声明:本文为lhy-index原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:http://www.cnblogs.com/lhy-index/p/7912120.html