NPOI导入导出Excel数据
代码:
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text; namespace CMS.Common
{
public class ExcelHelper : IDisposable
{
private string fileName = null; //文件名
private IWorkbook workbook = null;
private FileStream fs = null;
private bool disposed; public ExcelHelper(string fileName)
{
this.fileName = fileName;
disposed = false;
} /// <summary>
/// 将DataTable数据导入到excel中
/// </summary>
/// <param name="data">要导入的数据</param>
/// <param name="isColumnWritten">DataTable的列名是否要导入</param>
/// <param name="sheetName">要导入的excel的sheet的名称</param>
/// <returns>导入数据行数(包含列名那一行)</returns>
public int NPOIDataTableToExcel(DataTable data, string sheetName, bool isColumnWritten)
{
int i = ;
int j = ;
int count = ;
ISheet sheet = null; fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite);
if (fileName.IndexOf(".xlsx") > ) // 2007版本
workbook = new XSSFWorkbook();
else if (fileName.IndexOf(".xls") > ) // 2003版本
workbook = new HSSFWorkbook(); try
{
if (workbook != null)
{
sheet = workbook.CreateSheet(sheetName);
}
else
{
return -;
} if (isColumnWritten == true) //写入DataTable的列名
{
IRow row = sheet.CreateRow();
for (j = ; j < data.Columns.Count; ++j)
{
row.CreateCell(j).SetCellValue(data.Columns[j].ColumnName);
}
count = ;
}
else
{
count = ;
} for (i = ; i < data.Rows.Count; ++i)
{
IRow row = sheet.CreateRow(count);
for (j = ; j < data.Columns.Count; ++j)
{
row.CreateCell(j).SetCellValue(data.Rows[i][j].ToString());
}
++count;
}
workbook.Write(fs); //写入到excel
return count;
}
catch (Exception ex)
{
Console.WriteLine("Exception: " + ex.Message);
return -;
}
} /// <summary>
/// 将excel中的数据导入到DataTable中
/// </summary>
/// <param name="sheetName">excel工作薄sheet的名称</param>
/// <param name="isFirstRowColumn">第一行是否是DataTable的列名</param>
/// <returns>返回的DataTable</returns>
public DataTable NPOIExcelToDataTable(string sheetName, bool isFirstRowColumn)
{
ISheet sheet = null;
DataTable data = new DataTable();
int startRow = ;
try
{
fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
if (fileName.IndexOf(".xlsx") > ) // 2007版本
{
workbook = new XSSFWorkbook(fs);
}
else if (fileName.IndexOf(".xls") > ) // 2003版本
{
workbook = new HSSFWorkbook(fs);
}
if (sheetName != null)
{
sheet = workbook.GetSheet(sheetName);
if (sheet == null) //如果没有找到指定的sheetName对应的sheet,则尝试获取第一个sheet
{
sheet = workbook.GetSheetAt();
}
}
else
{
sheet = workbook.GetSheetAt();
}
if (sheet != null)
{
IRow firstRow = sheet.GetRow();
int cellCount = firstRow.LastCellNum; //一行最后一个cell的编号 即总的列数 if (isFirstRowColumn)
{
for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
{
ICell cell = firstRow.GetCell(i);
if (cell != null)
{
string cellValue = cell.StringCellValue;
if (cellValue != null)
{
DataColumn column = new DataColumn(cellValue);
data.Columns.Add(column);
}
}
}
startRow = sheet.FirstRowNum + ;
}
else
{
startRow = sheet.FirstRowNum;
}
//startRow = sheet.FirstRowNum + 1; //最后一列的标号
int rowCount = sheet.LastRowNum;
for (int i = startRow; i <= rowCount; ++i)
{
IRow row = sheet.GetRow(i);
if (row == null) continue; //没有数据的行默认是null DataRow dataRow = data.NewRow();
for (int j = row.FirstCellNum; j < cellCount; ++j)
{
if (row.GetCell(j) != null) //同理,没有数据的单元格都默认是null
dataRow[j] = row.GetCell(j).ToString();
}
data.Rows.Add(dataRow);
}
} return data;
}
catch (Exception ex)
{
Console.WriteLine("Exception: " + ex.Message);
return null;
}
} public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
} protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
if (fs != null)
fs.Close();
} fs = null;
disposed = true;
}
}
}
}
使用方法:
private DataTable dt = new DataTable();
protected void Button1_Click(object sender, EventArgs e)
{
Inidata();
string path = Server.MapPath("~/ExportData/" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xlsx");
int no = new Common.ExcelHelper(path).NPOIDataTableToExcel(dt, "sheet1", true);
}
/// <summary>
/// 装载数据
/// </summary>
private void Inidata()
{
dt.TableName = "sheet1";
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Team", typeof(string));
DataRow dr = dt.NewRow();
DataRow dr1 = dt.NewRow();
dr["Name"] = "科比";
dr["Team"] = "湖人";
dt.Rows.Add(dr);
dr1["Name"] = "詹姆斯";
dr1["Team"] = "骑士";
dt.Rows.Add(dr1);
}
最近发现,导出成 .xls 的已经不行了,只能导出 .xlsx 格式的。相关dll下载:http://pan.baidu.com/s/1o7KzI22
using Abp.Domain.Services;
using Newtonsoft.Json.Linq;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.IO;
using System.Text;
using System.Web; namespace Framework.Common
{
/// <summary>
/// Excel 导入导出
/// </summary>
public class ExcelHelper : DomainService
{
/// <summary>
/// 读取 Excel
/// 如果遇到整行为空行就停止读取并返回
/// </summary>
/// <param name="jsonHeader">
/// 返回 JSON 结构所需要字段名称,与 Excel 的列头相对应
/// </param>
/// <param name="sheetIndex">
/// 读取 Excel 时从 sheetIndex Sheet 开始读取,最小值为 0
/// </param>
/// <param name="startRowIndex">
/// 读取 Excel 时从 startRowIndex 行开始读取,最小值为 0
/// </param>
/// <param name="filePath">
/// 要读取的 Excel 文件路径
/// </param>
/// <returns></returns>
public JArray ReadExcel(string[] jsonHeader, int sheetIndex, int startRowIndex, string filePath)
{
if (sheetIndex < )
throw new Exception("sheetIndex 超出最小值,最小值为 0."); if (startRowIndex < )
throw new Exception("startRowIndex 超出最小值,最小值为 0."); if (!File.Exists(filePath))
throw new Exception("文件不存,请检查文件路径是否正确"); JArray array = new JArray();
XSSFWorkbook workbook = null;
using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
workbook = new XSSFWorkbook(fs);
}
var sheet = workbook.GetSheetAt(sheetIndex);
GetRow(array, jsonHeader, sheet, startRowIndex);
return array;
}
/// <summary>
/// 读取 Excel
/// 如果遇到整行为空行就停止读取并返回
/// </summary>
/// <param name="jsonHeader">
/// 返回 JSON 结构所需要字段名称,与 Excel 的列头相对应
/// </param>
/// <param name="sheetIndex">
/// 读取 Excel 时从 sheetIndex Sheet 开始读取,最小值为 0
/// </param>
/// <param name="startRowIndex">
/// 读取 Excel 时从 startRowIndex 行开始读取,最小值为 0
/// </param>
/// <param name="fs"></param>
/// <returns></returns>
public JArray ReadExcel(string[] jsonHeader, int sheetIndex, int startRowIndex, Stream fs)
{
if (sheetIndex < )
throw new Exception("sheetIndex 超出最小值,最小值为 0."); if (startRowIndex < )
throw new Exception("startRowIndex 超出最小值,最小值为 0."); JArray array = new JArray();
XSSFWorkbook workbook = new XSSFWorkbook(fs);
var sheet = workbook.GetSheetAt(sheetIndex);
GetRow(array, jsonHeader, sheet, startRowIndex);
return array;
} /// <summary>
/// 将数据导入到 Excel 模版
/// </summary>
/// <param name="array">
/// JArray 结构,需要导入到 Excel 中的数据
/// </param>
/// <param name="jsonHeader">
/// JSON 结构所需要字段名称,与 Excel 的列头相对应
/// </param>
/// <param name="sheetIndex">
/// 读取 Excel 时从 sheetIndex Sheet 开始读取,最小值为 0
/// </param>
/// <param name="startRowIndex">
/// 读取 Excel 时从 startRowIndex 行开始读取,最小值为 0
/// </param>
/// <param name="excelTempPath">
/// Excel 模版路径
/// </param>
/// <param name="exportFileName">
/// Excel 导出时的文件名称
/// </param>
/// <param name="context">
/// HttpContext 对象
/// </param>
public void ImportDataToExcel(JArray array, string[] jsonHeader, int sheetIndex, int startRowIndex, string excelTempPath, string exportFileName, HttpContext context)
{
if (sheetIndex < )
throw new Exception("sheetIndex 超出最小值,最小值为 0."); if (startRowIndex < )
throw new Exception("startRowIndex 超出最小值,最小值为 0."); if (!File.Exists(excelTempPath))
throw new Exception("文件不存,请检查文件路径是否正确"); IWorkbook workbook = null;
string tempExt = Path.GetExtension(excelTempPath).ToLower();
using (FileStream fs = File.Open(excelTempPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
if (tempExt == ".xls")
{
workbook = new HSSFWorkbook(fs);
}
else
{
workbook = new XSSFWorkbook(fs);
}
}
ISheet sheet = null;
if (tempExt == ".xls")
{
sheet = (HSSFSheet)workbook.GetSheetAt(sheetIndex);
}
else
{
sheet = (XSSFSheet)workbook.GetSheetAt(sheetIndex);
} IRow row = null;
ICell cell = null;
foreach (var item in array)
{
row = sheet.CreateRow(startRowIndex);
for (var h = ; h < jsonHeader.Length; h++)
{
cell = row.CreateCell(h);
cell.SetCellValue(item[jsonHeader[h]].Value<string>());
}
startRowIndex++;
} context.Response.ContentType = "application/vnd.ms-excel";
context.Response.AddHeader("Content-Disposition", "attachment;filename=" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xlsx");
context.Response.AddHeader("Content-Transfer-Encoding", "binary");
context.Response.ContentType = "application/octet-stream";
context.Response.ContentEncoding = Encoding.UTF8;
using (MemoryStream file = new MemoryStream())
{
workbook.Write(file);
byte[] buff = file.GetBuffer();
//context.Response.BinaryWrite(file.GetBuffer());//输出到浏览器 #region 输出文件
if (File.Exists(exportFileName))
{
File.Delete(exportFileName);
}
using (FileStream fs = new FileStream(exportFileName, FileMode.Create))
{
using (BinaryWriter bw = new BinaryWriter(fs))
{
bw.Write(buff, , buff.Length);
}
}
#endregion
}
} private void GetRow(JArray array, string[] jsonHeader, ISheet sheet, int rowIndex)
{
JObject json = new JObject();
var row = sheet.GetRow(rowIndex);
if (row != null)
{
var hasNext = false;
object val = string.Empty;
for (var i = ; i < jsonHeader.Length; i++)
{
var cell = row.GetCell(i);
if (cell == null)
{
val = null;
json[jsonHeader[i]] = string.Empty;
}
else
{
val = GetCellValue(json, jsonHeader[i], cell);
}
if (!hasNext && val != null)
{
// 若该行中,任意单元格不是 string.Empty 则将 hasNext 设置为 true 表示可以递归读取下一行
hasNext = true;
}
}
if (hasNext)
{
json["rowIndex"] = row.RowNum + ;
array.Add(json);
GetRow(array, jsonHeader, sheet, rowIndex + );
}
else
{
return;
}
}
} private object GetCellValue(JToken json, string head, ICell cell)
{ switch (cell.CellType)
{ case CellType.Error:
case CellType.Unknown:
case CellType.Blank:
return null; case CellType.Boolean:
json[head] = cell.BooleanCellValue;//.ToString();
return cell.BooleanCellValue;
case CellType.Numeric:
//对时间格式的处理
short format = cell.CellStyle.DataFormat;
if (format == || format == || format == || format == || format == )
{ json[head] = cell.DateCellValue;//.ToString("yyyy-mm-dd HH:mm:ss");
return cell.DateCellValue;
}
json[head] = cell.NumericCellValue;
return cell.NumericCellValue;//.ToString("N4");
}
json[head] = cell.StringCellValue;
return cell.StringCellValue;//.ToString("N4");
}
}
}
使用
string excelTempPath = System.Web.HttpContext.Current.Server.MapPath("~/TemplateFile/ItemTemp.xls");
string exportFileName = System.Web.HttpContext.Current.Server.MapPath("~/ExportFile/" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls"); string[] jsonHeader = new string[] { "Code", "Name"};
JArray array = new JArray();
foreach (var item in items)
{
JObject json = new JObject();
json["Code"] = item.Code;
json["Name"] = item.Name;
array.Add(json);
}
new ExcelHelp().ImportDataToExcel(array, jsonHeader, , , excelTempPath, exportFileName, System.Web.HttpContext.Current);
导出的时候,注意判断后缀名。.xls 使用 HSSFWorkbook,.xlsx 使用XSSFWorkbook
NPOI导入导出Excel数据的更多相关文章
- NPOI导入导出EXCEL通用类,供参考,可直接使用在WinForm项目中
以下是NPOI导入导出EXCEL通用类,是在别人的代码上进行优化的,兼容xls与xlsx文件格式,供参考,可直接使用在WinForm项目中,由于XSSFWorkbook类型的Write方法限制,Wri ...
- NPOI导入导出Excel
.net mvc利用NPOI导入导出excel 注意:如何导出的提交方式ajax导出是失效的! 解决方案是:js处理l两个表单的提交 代码: 第一步. 在页面里面加入2个隐藏的iframe, 如下 ...
- .Net core NPOI导入导出Excel
最近在想.net core NPOI 导入导出Excel,一开始感觉挺简单的,后来真的遇到很多坑.所以还是写一篇博客让其他人少走一些弯路,也方便忘记了再重温一遍.好了,多的不说,直接开始吧. 在.Ne ...
- 使用NPOI导入导出Excel(xls/xlsx)数据到DataTable中
using System; using System.Collections.Generic; using System.Text; using System.IO; using NPOI.SS.Us ...
- winfrom 使用NPOI导入导出Excel(xls/xlsx)数据到DataTable中
1.通过NUGET管理器下载nopi,在引入命令空间 using System; using System.Collections.Generic; using System.Text; using ...
- Npoi导入导出Excel操作
之前公司的一个物流商系统需要实现对订单的批量导入和导出,翻阅了一些资料,最后考虑使用NPOI实现这个需求. 在winform上面实现excel操作:http://www.cnblogs.com/Cal ...
- .net mvc利用NPOI导入导出excel
1.导出Excel :首先引用NPOI包(Action一定要用FileResult) /// <summary> /// 批量导出需要导出的列表 /// </summary> ...
- NPOI 导入导出excel 支持 03 07
因为微软的office成本太高了,所以开发项目的时候电脑上没安装office,而是安装了wps.但开发语言用的是C#,所以直接调用微软的office组件是很方便的,但一方面慢,一方面成本高,所以从网上 ...
- ASP.Net MVC利用NPOI导入导出Excel
因近期项目遇到所以记录一下: 首先导出Excel: 首先引用NPOI包 http://pan.baidu.com/s/1i3Fosux (Action一定要用FileResult) /// <s ...
随机推荐
- Java 类的生命周期
类从被加载到JVM内存中开始,到卸载出内存为止,它的整个生命周期包括: 加载(Loading)-->验证(Verification)-->准备(Preparation)-->解析(R ...
- while_else
使用while循环输出100-50,从大到小,到50的时候,再从0到50输出,然后结束count =
- storm的可靠性
消息确认机制: 在数据发送的过程中可能会数据丢失导致没能接收到,spout有个超时时间(默认是30S),如果30S过去了还是没有接收到数据,也认为是处理失败. 运行结果都是处理成功 参考代码Storm ...
- Neuromation新研究:利用卷积神经网络进行儿童骨龄评估
近日,Neuromation 团队在 Medium 上撰文介绍其最新研究成果:利用卷积神经网络(CNN)评估儿童骨龄,这一自动骨龄评估系统可以得到与放射科专家相似或更好的结果.该团队评估了手骨不同区域 ...
- shell中使用函数
函数定义.调用 $ cat te.sh #!/bin/bash # define a function test() { echo "This is a function." } ...
- CentOS7.3下yum练手安装Nginx,支持php5.4
yum install php php-devel 安装的是5.4 那么安装完毕了,怎么设置nginx和php 解析 1 添加nginx 默认主页index.php vim .../etc/ngin ...
- 网页向flash传参数。显示视频。(例子)
[例子1]网页向flash传参数,显示视频: 下面要做的事情:做一个flash文件,可以通过网页得到参数(视频文件名).然后显示视频,并在文本框中显示视频文件名的文字. 1.建立一个flash文件:3 ...
- sqoop1 使用测试
hive导入数据到mysql最简单的方式就是从hdfs直接读取hive表文件导入mysql,当然这需要知道数据表保存的目录 如果能直接从表到表的导入,无需路径,当然是最好了 1.需要下载合适的hive ...
- The type org.springframework.dao.support.DaoSupport cannot be resolved. It is indirectly referenced
springmvc mybatis整合,遇到错误:The type org.springframework.dao.support.DaoSupport cannot be resolved. It ...
- 使用matplotlib 制图(柱状图、箱型图)
柱状图: import pandas as pd import matplotlib.pyplot as plt data = pd.read_csv('D:\\myfiles\\study\\pyt ...