不依赖Excel是否安装的Excel导入导出类
本文利用第三方开源库NPOI实现Excel97-2003,Excel2007+的数据导入导出操作。
不依赖Office是否安装。NPOI开源项目地址:http://npoi.codeplex.com/。
库文件下载:http://npoi.codeplex.com/releases/view/115353
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Reflection;
using System.Text;
using System.Windows.Forms;
using NPOI.HPSF;
using NPOI.HSSF.UserModel;
using NPOI.HSSF.Util;
using NPOI.SS.UserModel;
using NPOI.SS.Util;
using NPOI.XSSF.UserModel;
using NPOI.XSSF.Util; namespace Youwei.Common
{
/// <summary>
/// Excel操作类。利用第三方开源库NPOI实现Excel97-2003。Excel2007+的数据导入导出操作。 不依赖Office是否安装。 /// NPOI开源项目地址:http://npoi.codeplex.com/
/// </summary>
public class ExcelHelper
{
private static String FilterExcel = "Excel文件 (*.xls;*.xlsx)|*.xls;*.xlsx"; /// <summary>
/// 从网格将数据导出到Excel,支持Excel97-2003(.xls)、Excel2007+(.xlsx)
/// </summary>
/// <param name="dgv">网格</param>
/// <param name="ignoredColumns">要忽略导出的列名称集合</param>
/// <param name="fileName">导出到的文件名称。为空时将弹出保存对话框</param>
public static void ExportToExcel(DataGridView dgv, List<string> ignoredColumns = null, string fileName = "")
{
if (String.IsNullOrEmpty(fileName))
fileName = Dialog.SaveFileDialog(FilterExcel); if (String.IsNullOrEmpty(fileName))
return; bool isSuccess = false;
IWorkbook workBook = null;
ISheet sheet = null;
IRow dataRow = null;
try
{
//不同格式实例化不同工作薄
if (fileName.EndsWith(".xls"))
workBook = new HSSFWorkbook();
else if (fileName.EndsWith(".xlsx"))
workBook = new XSSFWorkbook(); sheet = workBook.CreateSheet();
dataRow = sheet.CreateRow(0); //表头样式
ICellStyle headerStyle = workBook.CreateCellStyle();
headerStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
headerStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
headerStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
headerStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin; headerStyle.BottomBorderColor = NPOI.HSSF.Util.HSSFColor.Black.Index;
headerStyle.LeftBorderColor = HSSFColor.Black.Index;
headerStyle.RightBorderColor = HSSFColor.Black.Index;
headerStyle.TopBorderColor = HSSFColor.Black.Index; IFont font = workBook.CreateFont();
font.FontHeightInPoints = 10;
font.Boldweight = 700;
headerStyle.SetFont(font);
headerStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center; int i = 0, j = 0;
int ignoreCnt = 0;
//填充表头
for (i = 0; i < dgv.Columns.Count; i++)
{
if ((ignoredColumns != null && ignoredColumns.Contains(dgv.Columns[i].Name)) || !dgv.Columns[i].Visible || string.IsNullOrEmpty(dgv.Columns[i].HeaderText))
{
ignoreCnt++;
continue;
}
dataRow.CreateCell(i - ignoreCnt).SetCellValue(dgv.Columns[i].HeaderText);
dataRow.Cells[i - ignoreCnt].CellStyle = headerStyle;
} //内容样式
ICellStyle cellStyle = headerStyle;
cellStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Left;
font = workBook.CreateFont();
font.FontHeightInPoints = 10;
font.Boldweight = 100;
cellStyle.SetFont(font); //填充内容
DataGridViewCell cell = null;
for (i = 0; i < dgv.Rows.Count; i++)
{
dataRow = sheet.CreateRow(i + 1);
ignoreCnt = 0;
for (j = 0; j < dgv.Columns.Count; j++)
{
if ((ignoredColumns != null && ignoredColumns.Contains(dgv.Columns[j].Name)) || !dgv.Columns[j].Visible || string.IsNullOrEmpty(dgv.Columns[j].HeaderText))
{
ignoreCnt++;
continue;
}
cell = dgv[j, i];
if (cell is DataGridViewComboBoxCell)
dataRow.CreateCell(j - ignoreCnt).SetCellValue(ConvertHelper.ToString(cell.FormattedValue));
else
dataRow.CreateCell(j - ignoreCnt).SetCellValue(ConvertHelper.ToString(cell.Value));
dataRow.Cells[j - ignoreCnt].CellStyle = cellStyle;
}
} //写文件
using (MemoryStream ms = new MemoryStream())
{
using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write))
{
workBook.Write(ms);
ms.Flush();
ms.Position = 0;
byte[] data = ms.ToArray();
fs.Write(data, 0, data.Length);
fs.Flush();
data = null;
isSuccess = true;
}
} //打开文件
if (isSuccess && Dialog.Confirm("数据已经导出到Excel成功,你要打开吗?") == DialogResult.Yes)
{
Util.OpenFile(fileName);
}
}
catch (Exception ex)
{
Dialog.Error(ex, System.Reflection.MethodBase.GetCurrentMethod(), true);
}
finally
{
if (dataRow != null)
dataRow = null; if (sheet != null)
sheet = null; if (workBook != null)
{
workBook.Clear();
workBook = null;
}
}
} /// <summary>
/// 从Excel导入数据到实体类集合。支持Excel97-2003(.xls)、Excel2007+(.xlsx)
/// </summary>
/// <typeparam name="T">实体类</typeparam>
/// <param name="fileName">要导入的Excel文件名称。为空时将弹出保存对话框</param>
/// <param name="propertyTextNamePair">实体类属性的名称及属性名相应键值对</param>
/// <param name="startSheet">导入的起始Excel表单序号</param>
/// <param name="startRow">导入的起始Excel行号</param>
/// <param name="startColumn">导入的起始Excel列号</param>
/// <returns>泛型实体类集合</returns>
public static List<T> ImportFromExcel<T>(string fileName, Dictionary<string, string> propertyTextNamePair, int startSheet = 0, int startRow = 0, int startColumn = 0) where T : new()
{
List<T> list = new List<T>();
if (String.IsNullOrEmpty(fileName) || !System.IO.File.Exists(fileName))
fileName = Dialog.OpenFileDialog(FilterExcel); if (String.IsNullOrEmpty(fileName) || !System.IO.File.Exists(fileName))
return list; IWorkbook workBook = null;
ISheet sheet = null;
IRow row = null; try
{
//载入文档
using (FileStream fileStream = new FileStream(fileName, FileMode.Open))
{
//不同格式实例化不同工作薄
if (fileName.EndsWith(".xls"))
workBook = new HSSFWorkbook(fileStream);
else if (fileName.EndsWith(".xlsx"))
workBook = new XSSFWorkbook(fileStream);
} //载入指定工作薄
sheet = workBook.GetSheetAt(startSheet);
//workBook.NumberOfSheets //工作薄的表单数 //载入表头
IRow headerRow = sheet.GetRow(startRow);
ICell cellHeader = null;
ICell cell = null;
int cellCount = headerRow.LastCellNum; //获取实体类属性
Type type = typeof(T);
PropertyInfo[] ps = type.GetProperties();
T t = default(T);
PropertyInfo p = null; //遍历行列,赋值到实体类,并加入到实体类集合
for (int i = sheet.FirstRowNum + 1; i <= sheet.LastRowNum; i++)
{
row = sheet.GetRow(i);
t = new T();
for (int j = 0; j < cellCount; j++)
{
cellHeader = headerRow.GetCell(j);
cell = row.GetCell(j); if (propertyTextNamePair != null && propertyTextNamePair.ContainsKey(cellHeader.ToString()))
p = type.GetProperty(propertyTextNamePair[cellHeader.ToString()]);
else
p = type.GetProperty(cellHeader.ToString()); if (p != null)
p.SetValue(t, Convert.ChangeType(cell.ToString(), p.PropertyType), null);
}
list.Add(t);
} //回收资源
ps = null;
cellHeader = null;
headerRow = null;
}
catch (Exception ex)
{
Dialog.Error(ex, System.Reflection.MethodBase.GetCurrentMethod(), true);
}
finally
{
if (row != null)
row = null; if (sheet != null)
sheet = null; if (workBook != null)
{
workBook.Clear();
workBook = null;
}
} return list;
}
}
}
不依赖Excel是否安装的Excel导入导出类的更多相关文章
- Linux下mongodb安装及数据导入导出教程
Linux下mongodb安装及数据导入导出教程 #查看linux发行版本 cat /etc/issue #查看linux内核版本号 uname -r 一.Linux下mongodb安装的一般步骤 1 ...
- MinGW dll导入导出类
dll不仅可以导入导出函数,还可以导入导出类.这篇文章就来介绍如何将类导入dll中并导出. 首先我们建立一个名为dll.cpp的文件(又是这种破名字),里面写上: #include <iostr ...
- .net实现与excel的数据交互、导入导出
应该说,一套成熟的基于web的管理系统,与用户做好的excel表格进行数据交互是一个不可或缺的功能,毕竟,一切以方便客(jin)户(qian)为宗旨. 本人之前从事PHP的开发工作,熟悉PHP的都应该 ...
- sqoop1的安装以及数据导入导出测试
下载 wget http://mirror.bit.edu.cn/apache/sqoop/1.4.7/sqoop-1.4.7.bin__hadoop-2.6.0.tar.gz 解压 tar -zxf ...
- VC++导入导出类
一.导出类 VC++中导出类很简单,下面列出了两个等价的方法: 方法1: class __declspec(dllexport) CTest { public: int m_nValue ...
- 【tp5.1】composer安装PHPExcel以及导入\导出Excel
一.安装PHPExcel 1.下载:PHPExcel https://github.com/PHPOffice/PHPExcel 2.解压后:Classes文件夹改名为PHPExcel 3.把文件夹 ...
- .net core 基于NPOI 的excel导入导出类,支持自定义导出哪些字段,和判断导入是否有失败的记录
#region 从Excel导入 //用法 //var cellHeader = new Dictionary<string, string>(); //cellHeader.Add(&q ...
- SQL数据库与excel表格之间的数据 导入 导出
- ubuntu上安装mysql及导入导出
ubuntu上安装mysql: 1. sudo apt-get install mysql-server 2. apt-get isntall mysql-client3. sudo apt-get ...
随机推荐
- Robocopy用法
----------------[参数]-------------------robocopy /?------------------------------------------------- ...
- java.security.InvalidKeyException: IOException : Short read of DER length
今天支付服务器测试退款的时候爆了异常:Caused by: java.security.InvalidKeyException: IOException : Short read of DER len ...
- 转载~基于比较的排序算法的最优下界为什么是O(nlogn)
基于比较的排序算法的最优下界为什么是O(nlogn) 发表于2013/12/21 16:15:50 1024人阅读 分类: Algorithm 1.决策二叉树 回答这个问题之前我们先来玩一个猜数字的 ...
- 大(NOIP模拟赛Round #10)
题目描述: 小Z有个n个点的高清大图,每个点有且只有一条单向边的出边.现在你可以翻转其中的一些边,使他从任何一个点都不能通过一些道路走回这个点.为了方便,你只需输出方案数对取模即可.当在两个方案中有任 ...
- NS_AVAILABLE_IOS(6_0)
http://www.cocoachina.com/bbs/read.php?tid=241951 一个简单的小问题,请诸位大侠帮助给看看 ,新手 ,勿拍砖 本帖属于CocoaChina会 ...
- 7.0不通过FileProvider解决调用相机给uri问题异常
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {//严格模式 StrictMode.VmPolicy.Builder builder = ...
- Centos 查看内存
1. 查看内存使用 free -mh 2. 读出的内核信息进行解释 cat /proc/meminfo MemTotal: kB #所有可用RAM大小 (即物理内存减去一些预留位和内核的二进制代码大小 ...
- hdu 5109(构造数+对取模的理解程度)
Alexandra and A*B Problem Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Jav ...
- 学习hibernate,这个系列很不错
从这里入,感谢作者啊. 看了很多资料,这个是最能让我入门的.感觉. http://blog.csdn.net/yerenyuan_pku/article/details/52745486
- Python的程序结构[1] -> 方法/Method[0] -> 类实例方法、私有方法和抽象方法
类实例方法.私有方法和抽象方法 Python中最常用的就是类实例方法,类似于属性中的类实例属性,同时,也存在与私有属性类似方法,即私有方法,下面介绍这两种常见的方法,以及一种特殊意义的类实例方法 -- ...