1.首先到网上下载"NPOI.DLL"。引用。

2.新建一个操作类“ExcelHelper.cs”:

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(0); //表头
IRow header = sheet.GetRow(sheet.FirstRowNum);
List<int> columns = new List<int>();
for (int i = 0; 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 + 1; 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(0);
for (int i = 0; i < dt.Columns.Count; i++)
{
ICell cell = row.CreateCell(i);
cell.SetCellValue(dt.Columns[i].ColumnName);
} //数据
for (int i = 0; i < dt.Rows.Count; i++)
{
IRow row1 = sheet.CreateRow(i + 1);
for (int j = 0; 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, 0, 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(0); //表头
IRow header = sheet.GetRow(sheet.FirstRowNum);
List<int> columns = new List<int>();
for (int i = 0; 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 + 1; 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(0);
for (int i = 0; i < dt.Columns.Count; i++)
{
ICell cell = row.CreateCell(i);
cell.SetCellValue(dt.Columns[i].ColumnName);
} //数据
for (int i = 0; i < dt.Rows.Count; i++)
{
IRow row1 = sheet.CreateRow(i + 1);
for (int j = 0; 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, 0, 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;
}
}

3.程序后台主要代码:

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(10000);
var path = Server.MapPath("~/xls_down/" + name + ".xls");
var dt = new System.Data.DataTable();
var Columns=Enumerable.Range(1, 10).Select(d => new DataColumn("a"+d.ToString(), typeof(string))).ToArray();
dt.Columns.AddRange(Columns);
for (int i = 0; i < 33333; 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(10000);
var path = Server.MapPath("~/xls_down/" + name + ".xlsx");
var dt = new System.Data.DataTable();
var Columns = Enumerable.Range(1, 10).Select(d => new DataColumn("a" + d.ToString(), typeof(string))).ToArray();
dt.Columns.AddRange(Columns);
for (int i = 0; i < 33333; 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();
}
}

asp.net(C#)之NPOI&quot;操作Excel的更多相关文章

  1. ASP.Net MVC利用NPOI导入导出Excel

    因近期项目遇到所以记录一下: 首先导出Excel: 首先引用NPOI包 http://pan.baidu.com/s/1i3Fosux (Action一定要用FileResult) /// <s ...

  2. C# 之 用NPOI类库操作Excel

    1.需引用以下命名空间: using NPOI.HSSF.UserModel; using NPOI.SS.UserModel; using NPOI.HPSF; using NPOI.HSSF.Ut ...

  3. C#开发之基于NPOI的操作Excel开发体验

    最近遇到一个数据导入的需求,语言是.net framework 4.7的C#.但是,这次主要探讨NPOI的体验,原则就是向前兼容.所以采用.xls的支持.网上的资料,我稍微整合了一些. #1 单元格下 ...

  4. NPOI简单操作excel

    本文仅当是个记录文件,仅供初学者参考. 首先得using几个npoi的空间名如下: using NPOI.HSSF.UserModel;using NPOI.HSSF.Util;using NPOI. ...

  5. asp.net mvc 使用NPOI插件导出excel

    /// <summary> /// 交易账单 导出交易列表 /// </summary> /// <returns></returns> public ...

  6. NPOI读取操作excel

    .读取using (FileStream stream = new FileStream(@"c:\客户资料.xls", FileMode.Open, FileAccess.Rea ...

  7. Asp.net操作Excel(终极方法NPOI)(转)

    原文:Asp.net操作Excel(终极方法NPOI) 先去官网:http://npoi.codeplex.com/下载需要引入dll(可以选择.net2.0或者.net4.0的dll),然后在网站中 ...

  8. ASP.NET操作Excel(终极方法NPOI)

    ASP.NET操作Excel已经是老生长谈的事情了,可下面我说的这个NPOI操作Excel,应该是最好的方案了,没有之一,能够帮助开发者在没有安装微软Office的情况下读写Office 97-200 ...

  9. 免费高效实用的.NET操作Excel组件NPOI(.NET组件介绍之六)

    很多的软件项目几乎都包含着对文档的操作,前面已经介绍过两款操作文档的组件,现在介绍一款文档操作的组件NPOI. NPOI可以生成没有安装在您的服务器上的Microsoft Office套件的Excel ...

随机推荐

  1. net异步编程之await

    net异步编程之await 初探asp.net异步编程之await   终于毕业了,也顺利进入一家期望的旅游互联网公司.27号入职.放肆了一个多月没写代码,好方啊. 另外一下观点均主要针对于await ...

  2. WCF技术剖析之二十二: 深入剖析WCF底层异常处理框架实现原理[中篇]

    原文:WCF技术剖析之二十二: 深入剖析WCF底层异常处理框架实现原理[中篇] 在[上篇]中,我们分别站在消息交换和编程的角度介绍了SOAP Fault和FaultException异常.在服务执行过 ...

  3. mysql basic operation,mysql总结

    mysql> select * from wifi_data where dev_id like "0023-AABBCCCCBBAA" ; 1.显示数据库列表.show d ...

  4. [置顶] Oracle 11g ASM:如何在 ASMCMD 命令行工具中创建 Oracle ACFS 文件系统

    实验环境:Oracle 11g R2 RAC (11.2.0.3.5)                Oracle Enterprise Linux 5.6 x86 1.创建 ASM 磁盘组 在两节点 ...

  5. 怎样实现cocos2d-x之文字渲染

    // 1.创建一段文本 // create函数的三个参数分别为:文本内容.字体和字体大小 CCLabelTTF *font=CCLabelTTF::create("Hello World&q ...

  6. iOS &quot;The sandbox is not in sync with the Podfile.lock&quot;解决方式

    更新Cocoapod之后出现故障: diff: /../Podfile.lock: No such file or directory diff: Manifest.lock: No such fil ...

  7. extjs_04_grid(弹出窗口&amp;行编辑器 CRUD数据)

    1.弹出窗口(添加.删除) watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvYWRhbV93enM=/font/5a6L5L2T/fontsize/400/f ...

  8. 零积分下载,2014年辛星mysql教程秋季版第一本已经完工,期待您的支持

    经过一段时间的不懈努力.终于,2014年辛星mysql教程秋季版的第一本,即夯实基础已经完工,在csdn的下载地址为:去下载地址 ,假设左边地址跪了,能够去http://download.csdn.n ...

  9. iframe间的通信

    父框架 <body></body> <script type="text/javascript"> document.domain = '100 ...

  10. URAL 1018 (金典树形DP)

    连接:1018. Binary Apple Tree Time limit: 1.0 second Memory limit: 64 MB Let's imagine how apple tree l ...