不依赖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 ...
随机推荐
- Python学习笔记(Django篇)——4、继续完善视图层
在demo/views.py中添加这些代码: def detail(request, question_id): returnHttpResponse("You're looking at ...
- myeclipse maven web项目配置
启用maven:window-->preference-->MyEclipse-->Maven4MyEclipse, 勾选复选框(Enable Mave4MyEclipse feat ...
- zoj 3822 概率dp
/* 题目大意:一个n*m的棋盘,每天放一个棋子,每行每列至少有一个棋子时结束.求达到每行每列至少有一个棋子的天数的数学期望. */ #include <iostream> #includ ...
- 阿里云Centos 7 FTP(vsftp)服务安装及配置
#检查vsftpd是否安装 rpm -qa | grep vsftpd #检查vsftpd版本并安装 yum list vsftpd yum install vsftpd #设置开机启动 system ...
- xmlhelper类
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Xm ...
- 理想中的SQL语句条件拼接方式 (二)
问题以及想要的效果,不重复叙述,如果需要的请先看 理想中的SQL语句条件拼接方式 . 效果 现在有2个类映射数据库的2张表,结构如下: public class User { public int U ...
- C++ delete 两次
转载自:http://blog.csdn.net/jxluofeng/article/details/19766801 <问题>危险的代码: int* p=new int(1); de ...
- Linux c 目录操作函数scandir
头文件#include <dirent.h> 函数定义:int scandir(const char *dir,struct dirent **namelist,int (*filter ...
- 在windows系统上word转pdf
一.前言:我在做文件转换过程中遇到的一些坑,在这里记录下,因为项目需求,需要使用html转pdf,由于itext转换质量问题(一些Css属性不起作用),导致只能通过word文件作为跳板来转换到pdf文 ...
- [BZOJ1997][Hnoi2010]Planar 2-sat (联通分量) 平面图
1997: [Hnoi2010]Planar Time Limit: 10 Sec Memory Limit: 64 MBSubmit: 2317 Solved: 850[Submit][Stat ...