NPOI 读写Excel
实例功能概述:
1、支持Excel2003以及2007
2、支持Excel读取到DataTable(TableToExcel)
3、支持DataTable导出到Excel(TableToExcel)
4、支持WPF DataGrid导出到Excel(SelectedRowToExcel,AllRowToExcel)
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Data;
using Microsoft.Win32;
using Microsoft.Windows.Controls;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel; namespace LT.Utility
{
/// <summary>
/// FileName: NpoiExcelHelper.cs
/// CLRVersion: 4.0.30319.18052
/// Author: ZhangLei
/// Corporation: Litu
/// Description:Npoi Excel操作类封装
/// DateTime: 2016/1/24 23:01:21
/// </summary>
public class NpoiExcelHelper
{
#region Public Interface /// <summary>
/// 读取Excel到DataTable<see cref="System.Data.DataTable"/>
/// </summary>
/// <param name="file">Excel路径,如"E:\hello.xls"</param>
/// <returns></returns>
public static DataTable ExcelToTable(string file)
{
var type = GetFileType(file);
if ( type== FileType.Excel2003)
{
return ExcelToTableForXLS(file);
}
else if (type == FileType.Excel2007)
{
return ExcelToTableForXLSX(file);
}
else
{
return null;
}
} /// <summary>
/// DataTable 导出到 Excel
/// </summary>
/// <param name="dt"></param>
public static void TableToExcel(DataTable dt)
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "Excel 2003(*.xls)|*.xls|Excel 2007(*.xlsx)|*.xlsx";
saveFileDialog.FilterIndex = 1;
if (saveFileDialog.ShowDialog() == true)
{
if (saveFileDialog.FilterIndex == 1)
{
TableToExcelForXLS(dt,saveFileDialog.FileName);
}
else
{
TableToExcelForXLSX(dt, saveFileDialog.FileName);
}
}
} /// <summary>
/// DataTable 导出到 Excel
/// </summary>
/// <param name="dt"></param>
/// <param name="file">Excel路径,如"E:\hello.xls"</param>
public static void TableToExecel(DataTable dt, string file)
{
var type = GetFileType(file);
if (type == FileType.Excel2003)
{
TableToExcelForXLS(dt, file);
}
else if (type == FileType.Excel2007)
{
TableToExcelForXLSX(dt, file);
}
else
{
throw new Exception("暂不支持此种文件类型的输出");
}
} /// <summary>
/// WPF DataGrid选中行数据导出到Excel
/// </summary>
/// <param name="dataGrid"></param>
public static void SelectedRowToExcel(DataGrid dataGrid)
{
var dataView = dataGrid.ItemsSource as DataView;
if (dataView != null)
{
DataTable dt = dataView.ToTable();
dt.Rows.Clear();
int sRowCount = dataGrid.SelectedItems.Count;
int col = dataGrid.Columns.Count; var sItems = dataGrid.SelectedItems;
DataRow newRow = null;
DataRowView drv = null;
for (int i = 0; i < sRowCount; i++)
{
newRow = dt.NewRow();
for (int j = 0; j < col; j++)
{
drv = sItems[i] as DataRowView;
newRow[j] = drv[j];
}
dt.Rows.Add(newRow);
}
TableToExcel(dt);
}
else
{
throw new Exception("DataGrid 数据源为null,无法导出到Excel");
}
} /// <summary>
/// WPF DataGrid全部数据导出到Excel
/// </summary>
/// <param name="dataGrid"></param>
public static void AllRowToExcel(DataGrid dataGrid)
{
var dataView = dataGrid.ItemsSource as DataView;
if (dataView != null)
{
DataTable dt = dataView.ToTable();
TableToExcel(dt);
}
else
{
throw new Exception("DataGrid 数据源为null,无法导出到Excel");
}
}
#endregion #region Common Function private static FileType GetFileType(string file)
{
string extention = Path.GetExtension(file).ToLower();
if(extention.Equals(".xls"))
{
return FileType.Excel2003;
}
else if (extention.Equals(".xlsx"))
{
return FileType.Excel2007;
}
else
{
return FileType.Other;
}
} enum FileType
{
Excel2003,
Excel2007,
Other
}
#endregion #region Excel2003
/// <summary>
/// 将Excel文件中的数据读出到DataTable中(xls)
/// </summary>
/// <param name="file"></param>
/// <returns></returns>
private 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>
private static void TableToExcelForXLS(DataTable dt, string file)
{
NPOI.HSSF.UserModel.HSSFWorkbook hssfworkbook = new NPOI.HSSF.UserModel.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 #region Excel2007及以上版本
/// <summary>
/// 将Excel文件中的数据读出到DataTable中(xlsx)
/// </summary>
/// <param name="file"></param>
/// <returns></returns>
private static DataTable ExcelToTableForXLSX(string file)
{
DataTable dt = new DataTable();
using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read))
{
//NPOI.XSSF.UserModel 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>
private 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 } }
NPOI 读写Excel的更多相关文章
- NPOI读写Excel
1.整个Excel表格叫做工作表:WorkBook(工作薄),包含的叫页(工作表):Sheet:行:Row:单元格Cell. 2.NPOI是POI的C#版本,NPOI的行和列的index都是从0开始 ...
- 【转】NPOI读写Excel
1.整个Excel表格叫做工作表:WorkBook(工作薄),包含的叫页(工作表):Sheet:行:Row:单元格Cell. 2.NPOI是POI的C#版本,NPOI的行和列的index都是从0开始 ...
- NPOI读写Excel【转载】
参考示例:https://www.cnblogs.com/luxiaoxun/p/3374992.html 感谢! 1.整个Excel表格叫做工作表:WorkBook(工作薄),包含的叫页(工作表): ...
- 使用NPOI读写Excel、Word
NPOI 是 POI 项目的 .NET 版本.POI是一个开源的Java读写Excel.WORD等微软OLE2组件文档的项目. 使用 NPOI 你就可以在没有安装 Office 或者相应环境的机器上对 ...
- C#使用NPOI读写excel
本帖内容来自网络+自己稍作整理,已找不到原贴,侵删 个人比较习惯用NPOI操作excel,方便易理解.在宇宙第一IDE(笑)——VS2017中插入NPOI就很方便: 首先安装NPOI: 然后在.cs文 ...
- NPOI读写Excel组件封装Excel导入导出组件
后台管理系统多数情况会与Excel打交道,常见的就是Excel的导入导出,对于Excel的操作往往是繁琐且容易出错的,对于后台系统的导入导出交互过程往往是固定的,对于这部分操作,我们可以抽离出公共组件 ...
- Unity3d 使用NPOI读写Excel 遇到的问题
开发环境:unity5.3 NPOI(.net 2.0版 http://npoi.codeplex.com/) 运行环境:PC版, 其他平台没有测试 先上效果图: 实现步骤: 1.新建一个Exce ...
- C#使用NPOI读写Excel的注意事项
NPOI的基本使用参照:https://www.cnblogs.com/lixiaobin/p/NPOI.html 既存文档读取修改方法 *既存Excel文档修改保存注意使用FileMode.Crea ...
- 用插件NPOI读写excel
1.用插件NPOIusing NPOI.SS.UserModel;using NPOI.XSSF.UserModel;using NPOI.HSSF.UserModel; public class E ...
随机推荐
- ✡ leetcode 168. Excel Sheet Column Title 26进制数字 --------- java
Given a positive integer, return its corresponding column title as appear in an Excel sheet. For exa ...
- IplImage 结构解读(转)
typedef struct _IplImage { int nSize; /* IplImage大小 */ int ID; ...
- Django中ImageField的使用
http://blog.csdn.net/u013690521/article/details/38777213 from django.db import models from django.co ...
- javascript 中的 true 或 false
JavaScript中奇葩的假值 通常在以下语句结构中需要判断真假 if分支语句 while循环语句 for里的第二个语句 如 1 2 3 4 5 6 7 if (boo) { // do somet ...
- 请求rest web服务client
RestClient using System; using System.Globalization; using System.IO; using System.Net; using System ...
- WinForm中使用XML文件存储用户配置及操作本地Config配置文件
大家都开发winform程序时候会大量用到配置App.config作为保持用户设置的基本信息,比如记住用户名,这样的弊端就是每个人一些个性化的设置每次更新程序的时候会被覆盖. 故将配置文件分两大类: ...
- javascript性能优化总结二(转载)
上面一篇文章大致介绍了一些javascript当中使用的一些小技巧,当下这篇文章继续介绍一下内存管理.松散耦合.性能方面的一些小知识.为避免错误应该注意的点 内存管理 1.循环引用 如果循环引用中包含 ...
- 【MySQL】探究之null与not null
相信很多用了mysql很久的人,对这两个字段属性的概念还不是很清楚,一般会有以下疑问: 我字段类型是not null,为什么我可以插入空值 为毛not null的效率比null高 判断字段不为空的时候 ...
- TCP/UDP的接收包方式
UDP udp不是流式的,每次接收一个包,长度不超过(65535-28,总包长65535字节,包头28字节).所以UDP方式下不需要填写任何参数直接调用 $client->recv() 即可.注 ...
- WCF netTcp配置
服务端配置 <system.serviceModel> <bindings> <netTcpBinding> <binding name="netT ...