首页 技术 正文
技术 2022年11月7日
0 收藏 600 点赞 395 浏览 5588 个字

前言

做了好几个Excel、Word导出,用了HTTP流导出伪Excel文件、用过Office组件(这东西在生产环境下相当麻烦,各种权限,**)。

最后决定使用NPOI组件来导出,好处很多很多了,这里不多说。

这篇文章呢,主要说一下Excel导出的细节以及问题。

我在制作这个Demo的时候使用的环境:

Visual Studio 2010、Office 2013 、Framework .NET 3.5 、NPOI 1.2.5(至于为什么没有选最新版 稍后说)

完成后的截图

NPOI导出Excel – 自动适应中文宽度(帮助类下载)

从浏览器导出的Excel,打开并没有提示文件格式不对,这是真真的Excel格式。

从上图看出,列是自动适应了宽度了的,不会挤到一堆。

CreateSheet帮助类

        /// <summary>
/// 创建工作簿
/// </summary>
/// <param name="fileName">下载文件名</param>
/// <param name="dt">数据源</param>
public static void CreateSheet(string fileName, DataTable dt)
{
HSSFWorkbook workbook = new HSSFWorkbook();
MemoryStream ms = new MemoryStream(); //创建一个名称为Payment的工作表
ISheet paymentSheet = workbook.CreateSheet("Payment"); //数据源
DataTable tbPayment = dt; //头部标题
IRow paymentHeaderRow = paymentSheet.CreateRow(); //循环添加标题
foreach (DataColumn column in tbPayment.Columns)
paymentHeaderRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName); // 内容
int paymentRowIndex = ; foreach (DataRow row in tbPayment.Rows)
{
IRow newRow = paymentSheet.CreateRow(paymentRowIndex); //循环添加列的对应内容
foreach (DataColumn column in tbPayment.Columns)
{
newRow.CreateCell(column.Ordinal).SetCellValue(row[column].ToString());
} paymentRowIndex++;
} //列宽自适应,只对英文和数字有效
for (int i = ; i <= dt.Rows.Count; i++)
{
paymentSheet.AutoSizeColumn(i);
}
//获取当前列的宽度,然后对比本列的长度,取最大值
for (int columnNum = ; columnNum <= dt.Columns.Count; columnNum++)
{
int columnWidth = paymentSheet.GetColumnWidth(columnNum) / ;
for (int rowNum = ; rowNum <= paymentSheet.LastRowNum; rowNum++)
{
IRow currentRow;
//当前行未被使用过
if (paymentSheet.GetRow(rowNum) == null)
{
currentRow = paymentSheet.CreateRow(rowNum);
}
else
{
currentRow = paymentSheet.GetRow(rowNum);
} if (currentRow.GetCell(columnNum) != null)
{
ICell currentCell = currentRow.GetCell(columnNum);
int length = Encoding.Default.GetBytes(currentCell.ToString()).Length;
if (columnWidth < length)
{
columnWidth = length;
}
}
}
paymentSheet.SetColumnWidth(columnNum, columnWidth * );
} //将表内容写入流 通知浏览器下载
workbook.Write(ms);
System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.xls", fileName));
System.Web.HttpContext.Current.Response.BinaryWrite(ms.ToArray()); //进行二进制流下在 workbook = null;
ms.Close();
ms.Dispose();
} /// <summary>
/// 虚拟 DataTable内容
/// </summary>
/// <returns></returns>
public static DataTable CreatTable()
{
//创建DataTable 将数据库中没有的数据放到这个DT中
DataTable datatable = new DataTable();
datatable.Columns.Add("列1", typeof(string));
datatable.Columns.Add("列2", typeof(string));
datatable.Columns.Add("列3", typeof(string));
//创建DatatTable 结束--------------------------- //开始给临时datatable赋值
for (int i = ; i < ; i++)
{
DataRow row = datatable.NewRow();
row["列1"] = "列111111111111111111111111111111";
row["列2"] = "列222222222222222222222222222222222222222";
row["列3"] = "列3333333322222222222211111111111111111111111113";
datatable.Rows.Add(row);
}
return datatable;
}

代码中我加上了一个自己创建的DataTable作为数据源来进行导出,以免Demo用到数据库。

关于错误问题

当创建项目的版本高于NPOI基于的.net版本,会提示报错。

更换.net版本就行了。

另外官网提供的最新版是bate版本,我使用过程中会报错。还是选择2.0版本吧。

DEMO下载

360云盘 http://yunpan.cn/Qagu3ZYyYYqnW (提取码:0538)

再次更新(2015年11月16日 )

这次直接来一个简单的扩展,包含了泛型导出和DataTable导出:

     /// <summary>
/// Export扩展 - DataTable、泛型导出Excel
/// </summary>
public static class ExportExcel
{
/// <summary>
/// 导出Excel(03-07) 泛型集合操作
/// </summary>
/// <typeparam name="T">实体类型</typeparam>
/// <param name="lists">数据源</param>
/// <param name="fileName">下载文件名</param>
/// <returns></returns>
public static byte[] ListToExcel<T>(this IList<T> lists, string fileName)
{
using (MemoryStream ms = new MemoryStream())
{
HSSFWorkbook workbook = new HSSFWorkbook();
//创建一个名称为Payment的工作表
ISheet paymentSheet = workbook.CreateSheet("Payment");
//头部标题
IRow paymentHeaderRow = paymentSheet.CreateRow(); PropertyInfo[] propertys = lists[].GetType().GetProperties();
//循环添加标题
for (int i = ; i < propertys.Count(); i++)
paymentHeaderRow.CreateCell(i).SetCellValue(propertys[i].Name);
// 内容
int paymentRowIndex = ;
foreach (var each in lists)
{
IRow newRow = paymentSheet.CreateRow(paymentRowIndex);
//循环添加列的对应内容
for (int i = ; i < propertys.Count(); i++)
{
var obj = propertys[i].GetValue(each, null);
newRow.CreateCell(i).SetCellValue(obj.ToString());
}
paymentRowIndex++;
} //列宽自适应,只对英文和数字有效
for (int i = ; i <= lists.Count; i++)
paymentSheet.AutoSizeColumn(i);
//将表内容写入流 等待下一步操作
workbook.Write(ms);
return ms.ToArray();
}
} /// <summary>
/// 导出Excel(03-07) DataTable操作
/// </summary>
/// <param name="dt">数据源</param>
/// <param name="fileName">下载文件名</param>
/// <returns></returns>
public static byte[] ListToExcel(this DataTable dt, string fileName)
{
using (MemoryStream ms = new MemoryStream())
{
HSSFWorkbook workbook = new HSSFWorkbook();
//创建一个名称为Payment的工作表
ISheet paymentSheet = workbook.CreateSheet("Payment");
//数据源
DataTable tbPayment = dt;
//头部标题
IRow paymentHeaderRow = paymentSheet.CreateRow();
//循环添加标题
foreach (DataColumn column in tbPayment.Columns)
paymentHeaderRow.CreateCell(column.Ordinal).SetCellValue(column.ColumnName);
// 内容
int paymentRowIndex = ;
foreach (DataRow row in tbPayment.Rows)
{
IRow newRow = paymentSheet.CreateRow(paymentRowIndex);
//循环添加列的对应内容
foreach (DataColumn column in tbPayment.Columns)
newRow.CreateCell(column.Ordinal).SetCellValue(row[column].ToString());
paymentRowIndex++;
} //列宽自适应,只对英文和数字有效
for (int i = ; i <= dt.Rows.Count; i++)
paymentSheet.AutoSizeColumn(i);
//获取当前列的宽度,然后对比本列的长度,取最大值
for (int columnNum = ; columnNum <= dt.Columns.Count; columnNum++)
{
int columnWidth = paymentSheet.GetColumnWidth(columnNum) / ;
for (int rowNum = ; rowNum <= paymentSheet.LastRowNum; rowNum++)
{
//当前行未被使用过
var currentRow = paymentSheet.GetRow(rowNum) ?? paymentSheet.CreateRow(rowNum);
if (currentRow.GetCell(columnNum) != null)
{
ICell currentCell = currentRow.GetCell(columnNum);
int length = Encoding.Default.GetBytes(currentCell.ToString()).Length;
if (columnWidth < length)
columnWidth = length;
}
}
paymentSheet.SetColumnWidth(columnNum, columnWidth * );
}
//将表内容写入流 等待其他操作
workbook.Write(ms);
return ms.ToArray();
}
}
}

相关资料

解决自适应宽不支持中文问题: http://blog.csdn.net/jerry_cool/article/details/7000085

NPOI官网:http://npoi.codeplex.com/

NPOI大全:http://www.cnblogs.com/atao/category/209358.html

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,491
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,907
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,740
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,492
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,132
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,293