using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel; public class ExcelHelper
{
public class x2003
{
#region Excel2003
/// <summary>
/// 将Excel文件中的数据读出到DataTable中(xls)
/// </summary>
/// <param name="file"></param>
/// <returns></returns>
public static DataTable ExcelToTableForXLS(string file)
{
DataTable dt = new DataTable();
using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read))
{
HSSFWorkbook hssfworkbook = new HSSFWorkbook(fs);
ISheet sheet = hssfworkbook.GetSheetAt(); //表头
IRow header = sheet.GetRow(sheet.FirstRowNum);
List<int> columns = new List<int>();
for (int i = ; i < header.LastCellNum; i++)
{
object obj = GetValueTypeForXLS(header.GetCell(i) as HSSFCell);
if (obj == null || obj.ToString() == string.Empty)
{
dt.Columns.Add(new DataColumn("Columns" + i.ToString()));
//continue;
}
else
dt.Columns.Add(new DataColumn(obj.ToString()));
columns.Add(i);
}
//数据
for (int i = sheet.FirstRowNum + ; i <= sheet.LastRowNum; i++)
{
DataRow dr = dt.NewRow();
bool hasValue = false;
foreach (int j in columns)
{
dr[j] = GetValueTypeForXLS(sheet.GetRow(i).GetCell(j) as HSSFCell);
if (dr[j] != null && dr[j].ToString() != string.Empty)
{
hasValue = true;
}
}
if (hasValue)
{
dt.Rows.Add(dr);
}
}
}
return dt;
} /// <summary>
/// 将DataTable数据导出到Excel文件中(xls)
/// </summary>
/// <param name="dt"></param>
/// <param name="file"></param>
public static void TableToExcelForXLS(DataTable dt, string file)
{
HSSFWorkbook hssfworkbook = new HSSFWorkbook();
ISheet sheet = hssfworkbook.CreateSheet("Test"); //表头
IRow row = sheet.CreateRow();
for (int i = ; i < dt.Columns.Count; i++)
{
ICell cell = row.CreateCell(i);
cell.SetCellValue(dt.Columns[i].ColumnName);
} //数据
for (int i = ; i < dt.Rows.Count; i++)
{
IRow row1 = sheet.CreateRow(i + );
for (int j = ; j < dt.Columns.Count; j++)
{
ICell cell = row1.CreateCell(j);
cell.SetCellValue(dt.Rows[i][j].ToString());
}
} //转为字节数组
MemoryStream stream = new MemoryStream();
hssfworkbook.Write(stream);
var buf = stream.ToArray(); //保存为Excel文件
using (FileStream fs = new FileStream(file, FileMode.Create, FileAccess.Write))
{
fs.Write(buf, , buf.Length);
fs.Flush();
}
} /// <summary>
/// 获取单元格类型(xls)
/// </summary>
/// <param name="cell"></param>
/// <returns></returns>
private static object GetValueTypeForXLS(HSSFCell cell)
{
if (cell == null)
return null;
switch (cell.CellType)
{
case CellType.Blank: //BLANK:
return null;
case CellType.Boolean: //BOOLEAN:
return cell.BooleanCellValue;
case CellType.Numeric: //NUMERIC:
return cell.NumericCellValue;
case CellType.String: //STRING:
return cell.StringCellValue;
case CellType.Error: //ERROR:
return cell.ErrorCellValue;
case CellType.Formula: //FORMULA:
default:
return "=" + cell.CellFormula;
}
}
#endregion
} public class x2007
{
#region Excel2007
/// <summary>
/// 将Excel文件中的数据读出到DataTable中(xlsx)
/// </summary>
/// <param name="file"></param>
/// <returns></returns>
public static DataTable ExcelToTableForXLSX(string file)
{
DataTable dt = new DataTable();
using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read))
{
XSSFWorkbook xssfworkbook = new XSSFWorkbook(fs);
ISheet sheet = xssfworkbook.GetSheetAt(); //表头
IRow header = sheet.GetRow(sheet.FirstRowNum);
List<int> columns = new List<int>();
for (int i = ; i < header.LastCellNum; i++)
{
object obj = GetValueTypeForXLSX(header.GetCell(i) as XSSFCell);
if (obj == null || obj.ToString() == string.Empty)
{
dt.Columns.Add(new DataColumn("Columns" + i.ToString()));
//continue;
}
else
dt.Columns.Add(new DataColumn(obj.ToString()));
columns.Add(i);
}
//数据
for (int i = sheet.FirstRowNum + ; i <= sheet.LastRowNum; i++)
{
DataRow dr = dt.NewRow();
bool hasValue = false;
foreach (int j in columns)
{
dr[j] = GetValueTypeForXLSX(sheet.GetRow(i).GetCell(j) as XSSFCell);
if (dr[j] != null && dr[j].ToString() != string.Empty)
{
hasValue = true;
}
}
if (hasValue)
{
dt.Rows.Add(dr);
}
}
}
return dt;
} /// <summary>
/// 将DataTable数据导出到Excel文件中(xlsx)
/// </summary>
/// <param name="dt"></param>
/// <param name="file"></param>
public static void TableToExcelForXLSX(DataTable dt, string file)
{
XSSFWorkbook xssfworkbook = new XSSFWorkbook();
ISheet sheet = xssfworkbook.CreateSheet("Test"); //表头
IRow row = sheet.CreateRow();
for (int i = ; i < dt.Columns.Count; i++)
{
ICell cell = row.CreateCell(i);
cell.SetCellValue(dt.Columns[i].ColumnName);
} //数据
for (int i = ; i < dt.Rows.Count; i++)
{
IRow row1 = sheet.CreateRow(i + );
for (int j = ; j < dt.Columns.Count; j++)
{
ICell cell = row1.CreateCell(j);
cell.SetCellValue(dt.Rows[i][j].ToString());
}
} //转为字节数组
MemoryStream stream = new MemoryStream();
xssfworkbook.Write(stream);
var buf = stream.ToArray(); //保存为Excel文件
using (FileStream fs = new FileStream(file, FileMode.Create, FileAccess.Write))
{
fs.Write(buf, , buf.Length);
fs.Flush();
}
} /// <summary>
/// 获取单元格类型(xlsx)
/// </summary>
/// <param name="cell"></param>
/// <returns></returns>
private static object GetValueTypeForXLSX(XSSFCell cell)
{
if (cell == null)
return null;
switch (cell.CellType)
{
case CellType.Blank: //BLANK:
return null;
case CellType.Boolean: //BOOLEAN:
return cell.BooleanCellValue;
case CellType.Numeric: //NUMERIC:
return cell.NumericCellValue;
case CellType.String: //STRING:
return cell.StringCellValue;
case CellType.Error: //ERROR:
return cell.ErrorCellValue;
case CellType.Formula: //FORMULA:
default:
return "=" + cell.CellFormula;
}
}
#endregion
} public static DataTable GetDataTable(string filepath)
{
var dt = new DataTable("xls");
if (filepath.Last()=='s')
{
dt = x2003.ExcelToTableForXLS(filepath);
}
else
{
dt = x2007.ExcelToTableForXLSX(filepath);
}
return dt;
}
}
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Linq;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{ }
protected void btn_read_03_click(object o, EventArgs e)
{
var dt = ExcelHelper.GetDataTable(Server.MapPath("~/xls_tmp/2003.xls"));
g1.DataSource = dt;
g1.DataBind();
}
protected void btn_read_07_click(object o, EventArgs e)
{
var dt = ExcelHelper.GetDataTable(Server.MapPath("~/xls_tmp/2007.xlsx"));
g1.DataSource = dt;
g1.DataBind();
}
protected void btn_import_03_click(object o, EventArgs e)
{
var name = DateTime.Now.ToString("yyyyMMddhhmmss") + new Random(DateTime.Now.Second).Next();
var path = Server.MapPath("~/xls_down/" + name + ".xls");
var dt = new System.Data.DataTable();
var Columns=Enumerable.Range(, ).Select(d => new DataColumn("a"+d.ToString(), typeof(string))).ToArray();
dt.Columns.AddRange(Columns);
for (int i = ; i < ; i++)
{
var id = Guid.NewGuid().ToString();
dt.Rows.Add(id, id, id, id, id, id, id, id, id, id);
}
ExcelHelper.x2003.TableToExcelForXLS(dt, path);
downloadfile(path);
}
protected void btn_import_07_click(object o, EventArgs e)
{
var name = DateTime.Now.ToString("yyyyMMddhhmmss") + new Random(DateTime.Now.Second).Next();
var path = Server.MapPath("~/xls_down/" + name + ".xlsx");
var dt = new System.Data.DataTable();
var Columns = Enumerable.Range(, ).Select(d => new DataColumn("a" + d.ToString(), typeof(string))).ToArray();
dt.Columns.AddRange(Columns);
for (int i = ; i < ; i++)
{
var id = Guid.NewGuid().ToString();
dt.Rows.Add(id, id, id, id, id, id, id, id, id, id);
}
ExcelHelper.x2007.TableToExcelForXLSX(dt, path);
downloadfile(path);
}
void downloadfile(string s_path)
{
System.IO.FileInfo file = new System.IO.FileInfo(s_path);
HttpContext.Current.Response.ContentType = "application/ms-download";
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader("Content-Type", "application/octet-stream");
HttpContext.Current.Response.Charset = "utf-8";
HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + System.Web.HttpUtility.UrlEncode(file.Name, System.Text.Encoding.UTF8));
HttpContext.Current.Response.AddHeader("Content-Length", file.Length.ToString());
HttpContext.Current.Response.WriteFile(file.FullName);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.End();
}
}

如果要提高效能千萬切記,不要在內循環中亂用下面的設定,要不效能就是幾秒與幾分鐘的差異。

sheet.AutoSizeColumn(cellIndex, true);

ICellStyle style = workbook.CreateCellStyle();
style.BorderBottom = BorderStyle.Thin;
style.BorderLeft = BorderStyle.Thin;
style.BorderRight = BorderStyle.Thin;
style.BorderTop = BorderStyle.Thin;

cell.CellStyle = style;

NPOI 单元格格式设置 http://blog.csdn.net/lcnmdfx/article/details/38083887

NPOI自适应宽度不支持中文解决方案 http://blog.csdn.net/jerry_cool/article/details/7000085

http://download.csdn.net/detail/diaodiaop/7611721

NPOI高效匯出Excel的更多相关文章

  1. T100-----汇出EXCEL表格

    例子:cxmp541 #excel匯出功能 ON ACTION exporttoexcel LET g_action_choice="exporttoexcel" IF cl_au ...

  2. NPOI导出数据到Excel

    NPOI导出数据到Excel   前言 Asp.net操作Excel已经是老生长谈的事情了,可下面我说的这个NPOI操作Excel,应该是最好的方案了,没有之一,使用NPOI能够帮助开发者在没有安装微 ...

  3. asp.net mvc4 easyui datagrid 增删改查分页 导出 先上传后导入 NPOI批量导入 导出EXCEL

    效果图 数据库代码 create database CardManage use CardManage create table CardManage ( ID ,) primary key, use ...

  4. 使用NPOI导出,读取EXCEL(可追加功能)

    使用NPOI导出,读取EXCEL,具有可追加功能 看代码 using System; using System.Collections.Generic; using System.Text; usin ...

  5. WeihanLi.Npoi 根据模板导出Excel

    WeihanLi.Npoi 根据模板导出Excel Intro 原来的导出方式比较适用于比较简单的导出,每一条数据在一行,数据列虽然自定义程度比较高,如果要一条数据对应多行就做不到了,于是就想支持根据 ...

  6. NPOI MVC 模型导出Excel通用类

    通用类: public enum DataTypeEnum { Int = , Float = , Double = , String = , DateTime = , Date = } public ...

  7. NPOI 导入,导出EXCEL

    代码: public static class NPOIExcelHelper { /// <summary> /// DataTable导出到Excel文件 /// </summa ...

  8. PHP 高效导入导出Excel(csv)方法之fgetcsv()和fputcsv()函数

    CSV,是Comma Separated Value(逗号分隔值)的英文缩写,通常都是纯文本文件. 一.CSV数据导入函数fgetcsv() fgetcsv() 函数从文件指针中读入一行并解析 CSV ...

  9. 在Asp.Net MVC中使用NPOI插件实现对Excel的操作(导入,导出,合并单元格,设置样式,输入公式)

    前言 NPOI 是 POI 项目的.NET版本,它不使用 Office COM 组件,不需要安装 Microsoft Office,目前支持 Office 2003 和 2007 版本. 1.整个Ex ...

随机推荐

  1. ExtJs 入门教程

    http://www.cnblogs.com/iamlilinfeng/archive/2012/12/31/2840663.html

  2. oracle参数与启停

    oracle随系统启动而启动 cs65-64桌面版orcle-11.2.0.4 启动监听器,后台进程,OEM. 注意: 如果只做一和三,只能启动后台进程,监听器不启动,如果只做二和三,只能启动监听器, ...

  3. 将n阶方阵左下半三角中的元素值置0.

    /*===================================== 将n阶方阵左下半三角中的元素值置0. 0<n<10. =========================== ...

  4. 【转】windows7的桌面右键菜单的“新建”子菜单,在注册表哪个位置,如何在“新建"里面添加一个新项

    点击桌面,就会弹出菜单,然后在“新建”中就又弹出可以新建的子菜单栏.office与txt 的新建都是在这里面的.我想做的事情是:在右键菜单的“新建” 中添加一个“TQ文本”的新建项,然后点击它之后,桌 ...

  5. C#中的List<string>泛型类示例

    在C#代码中使用一系列字符串(strings)并需要为其创建一个列表时,List<string>泛型类是一个用于存储一系列字 符串(strings)的极其优秀的解决办法.下面一起有一些Li ...

  6. 如何解决Oracle 11g EM网站报“此网站的安全证书存在问题”

    在IE中输入https://localhost:1158/em 接报错,打不开;提示:“证书错误,此网站安全证书有问题”,解决过程如下: 1.删除与重建dbconsole 2.配置必要的环境变量 1. ...

  7. Oracle序列使用:建立、删除

    转自:http://www.cnblogs.com/WangPB/archive/2010/07/13/1776766.html 在开始讲解Oracle序列使用方法之前,先加一点关于Oracle cl ...

  8. elasticsearch 集群配置

    2015-10-10 09:56 by 轩脉刃, 999 阅读, 1 评论, 收藏, 编辑 elasticsearch 集群 搭建elasticsearch的集群 现在假设我们有3台es机器,想要把他 ...

  9. CERT_KEY_CONTEXT_PROP_ID,CERT_KEY_PROV_INFO_PROP_ID,CERT_KEY_PROV_HANDLE_PROP_ID和CERT_KEY_SPEC_PROP_ID

    上面四个属性是CertSetCertificateContextProperty或CertGetCertificateContextProperty可以为证书上下文设置的几个属性,下面对它们的关联简单 ...

  10. bzoj4109: [Wf2015]Cutting Cheese

    Description 给定一个100*100*100(单位:毫米)的奶酪方块,这个奶酪含有n个球形小孔.现在要求将这个奶酪切成s片使得每片质量相等. Input 第一行包含两个整数n,s,表示奶酪有 ...