不依赖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 ...
随机推荐
- getElementsByName
name属性,name属性是input标签的内建属性,早期浏览器的getElementsByName方法是为了方便的获取用户的输入.由于name只是input的内建属性,其它标签没有,所以getEle ...
- [bzoj2127]happiness——最小割
这个题太恶心了...并不想继续做了... 本代码在bzoj上TLE! 大致说一下思路: 建立ST,首先由S连边(S,u,a)a代表学文的分数,连向T(u,T,b)b表示学理的分数,这样构造出了两个人独 ...
- Linux/Android——input_handler之evdev (四) 【转】
转自:http://blog.csdn.net/u013491946/article/details/72638919 版权声明:免责声明: 本人在此发文(包括但不限于汉字.拼音.拉丁字母)均为随意敲 ...
- Django和SQLAlchemy区别
译者注:本文首先介绍了什么是ORM,然后从多个方面对Python语言下的两个ORM库Django和SQLAlchemy进行比较,为ORM的选型提供了较为全面的指导建议.以下是译文. ORM是什么? 在 ...
- 使用EventHandler传递参数
1.MouseEventHandler和EventHandler传递参数的局限性分析 开发过程中,特别是使用自定义控件时,常常需要对一个控件的click,mouseDown,mouseUp等事件的处理 ...
- C. Heidi and Library (神奇的网络流)
C. Heidi and Library 题意 有 n 种分别具有价格 b 的书 a ,图书馆里最多同时存放 k 本书,已知接下来 n 天每天都有一个人来看某一本书,如果图书馆里没有则需要购买,问最少 ...
- 洛谷—— P1680 奇怪的分组
https://www.luogu.org/problemnew/show/1680 题目背景 终于解出了dm同学的难题,dm同学同意帮v神联络.可dm同学有个习惯,就是联络同学的时候喜欢分组联络,而 ...
- Sum of bit differences among all pairs
This article was found from Geeksforgeeks.org. Click here to see the original article. Given an inte ...
- 如何避免CSS :before、:after 中文乱码
问题: 在进行页面开发时,经常会使用:before, :after伪元素创建一些小tips,但是在:before或:after的content属性使用中文的话,会导致某些浏览器上出现乱码. 解决方案: ...
- iOS9 Storyboard unwind segue反回传递事件时机详细步骤
当返回上一个界面且需要上一个界面做某事时,用unwind segue实现起来比delegate简单许多,甚至有时不适合用delegate来实现,那么我们就用unwind segue吧,而且像1-> ...