如何使用NPOI 导出到excel和导入excel到数据库
近期一直在做如何将数据库的数据导出到excel和导入excel到数据库。
首先进入官网进行下载NPOI插件(http://npoi.codeplex.com/)。
我用的NPOI1.2.5稳定版。
使用这个网址http://tonyqus.sinaapp.com/可以查询你需要的一些资料。
我这次主要做的是数据库的数据导出到excel和导入excel到数据库。下来我说一下自己的思路。
DBToExcel
1.先建一个Model代码如下
public class person{
public string PersonId { get; set; }
public string PersonName { get; set; }
public string PersonSex { get; set; }
public string PersonIdCard { get; set; }
}
2.将person转换成list.
public static List<Person> GetData()
{
Person person = new Person {PersonId = };
person.PersonName = "张三";
person.PersonSex = "男";
person.PersonIdCard = ;
Person person1 = new Person
{
PersonId = ,
PersonName = "李四",
PersonSex = "女",
PersonIdCard =
};
Person person2 = new Person
{
PersonId = ,
PersonName = "王二",
PersonSex = "男",
PersonIdCard =
};
Person person3 = new Person
{
PersonId = ,
PersonName = "麻子",
PersonSex = "女",
PersonIdCard =
}; List<Person> list = new List<Person>(); list.Add(person);
list.Add(person1);
list.Add(person2);
list.Add(person3); return list;
}
3.将list转换成dataset或者datatable
public static DataSet ConvertToDataSet<T>(List<T> list)
{
if (list == null || list.Count <= 0)
{
return null;
}
DataSet ds = new DataSet();
DataTable dt = new DataTable(typeof(T).Name);
DataColumn column;
DataRow row;
System.Reflection.PropertyInfo[] myPropertyInfo = typeof(T).GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);
foreach (T t in list)
{
if (t == null)
{
continue;
}
row = dt.NewRow();
for (int i = 0, j = myPropertyInfo.Length; i < j; i++)
{
System.Reflection.PropertyInfo pi = myPropertyInfo[i];
string name = pi.Name;
if (dt.Columns[name] == null)
{
column = new DataColumn(name, pi.PropertyType);
dt.Columns.Add(column);
}
row[name] = pi.GetValue(t, null);
}
dt.Rows.Add(row);
}
ds.Tables.Add(dt);
return ds;
}
4.将Datatable转换成Excel
public static HSSFWorkbook DtToExcel(DataSet ds, string sheetName, string workName, string path)
{
HSSFWorkbook hassfworkbook = new HSSFWorkbook();
DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
dsi.Company = "NPOI Team";
hassfworkbook.DocumentSummaryInformation = dsi; SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
si.Subject = "NPOI SDK Example";
hassfworkbook.SummaryInformation = si; HSSFSheet sheet1 = (HSSFSheet)hassfworkbook.CreateSheet(sheetName);
HSSFRow row;
HSSFCell cell; //写字段名
row = (HSSFRow)sheet1.CreateRow();
for (int i = ; i < ds.Tables[].Columns.Count; i++)
{
cell = (HSSFCell)row.CreateCell(i);
cell.SetCellValue(String.Format(ds.Tables[].Columns[i].ColumnName));
}
//写记录
for (int rowIndex = ; rowIndex < ds.Tables[].Rows.Count; rowIndex++)
{
row = (HSSFRow)sheet1.CreateRow(rowIndex + );
for (int colIndex = ; colIndex < ds.Tables[].Columns.Count; colIndex++)
{
cell = (HSSFCell)row.CreateCell(colIndex);
cell.SetCellValue(String.Format(ds.Tables[].Rows[rowIndex][colIndex].ToString()));
}
} //前台调用
// HSSFWorkbook a= .DtToExcel(....)
//a.Write(Response.OutputStream)
////替换以下两句:
//hassfworkbook.Write(HttpContext.Current.Response.outputStrem);
//FileStream file = new FileStream(path + "/" + workName + ".cls", FileMode.Create);
//hassfworkbook.Write(file);
//file.Close();
return hassfworkbook;
}
下面把我自己写测试类给大家看看,代码如下。
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using NPOI.HPSF;
using NPOI.HSSF.UserModel;
using Test.Model;
namespace Test
{
class Test
{
private static string sheetName = "测试";
private static string workName = "test2";
private static string path = "D:";
public static void Main(string[] args)
{
//ConvertToDataSet(GetData());
//前台调用
HSSFWorkbook hassfworkbook = DtToExcel(ConvertToDataSet(GetData()), sheetName, workName, path);
//a.Write(Response.OutputStream)
////替换以下两句:
//hassfworkbook.Write(HttpContext.Current.Response.outputStrem);
FileStream file = new FileStream(path + "/" + workName + ".xls", FileMode.Create);
hassfworkbook.Write(file);
file.Close();
//DtToExcel(ConvertToDataSet(GetData()), sheetName, workName, path);
}
public static List<Person> GetData()
{
Person person = new Person {PersonId = 0};
person.PersonName = "张三";
person.PersonSex = "男";
person.PersonIdCard = 1245896352145825841;
Person person1 = new Person
{
PersonId = 1,
PersonName = "李四",
PersonSex = "女",
PersonIdCard = 1245896352145825841
};
Person person2 = new Person
{
PersonId = 2,
PersonName = "王二",
PersonSex = "男",
PersonIdCard = 1245896352145825841
};
Person person3 = new Person
{
PersonId = 3,
PersonName = "麻子",
PersonSex = "女",
PersonIdCard = 1245896352145825841
};
List<Person> list = new List<Person>();
list.Add(person);
list.Add(person1);
list.Add(person2);
list.Add(person3);
return list;
}
public static DataSet ListToDataSet<T>(List<Person> list)
{
if (list.Count==0) return new DataSet();
var properties = list[0].GetType().GetProperties();
var cols = properties.Select(p => new DataColumn(p.Name));
var dt = new DataTable();
dt.Columns.AddRange(cols.ToArray());
//list.ForEach(x => dt.Rows.Add(properties.Select(p => p.GetValue(x)).ToArray()));
return new DataSet {Tables = {dt}};
}
public static DataSet ConvertToDataSet<T>(List<T> list)
{
if (list == null || list.Count <= 0)
{
return null;
}
DataSet ds = new DataSet();
DataTable dt = new DataTable(typeof(T).Name);
DataColumn column;
DataRow row;
System.Reflection.PropertyInfo[] myPropertyInfo = typeof(T).GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);
foreach (T t in list)
{
if (t == null)
{
continue;
}
row = dt.NewRow();
for (int i = 0, j = myPropertyInfo.Length; i < j; i++)
{
System.Reflection.PropertyInfo pi = myPropertyInfo[i];
string name = pi.Name;
if (dt.Columns[name] == null)
{
column = new DataColumn(name, pi.PropertyType);
dt.Columns.Add(column);
}
row[name] = pi.GetValue(t, null);
}
dt.Rows.Add(row);
}
ds.Tables.Add(dt);
return ds;
}
public static HSSFWorkbook DtToExcel(DataSet ds, string sheetName, string workName, string path)
{
HSSFWorkbook hassfworkbook = new HSSFWorkbook();
DocumentSummaryInformation dsi = PropertySetFactory.CreateDocumentSummaryInformation();
dsi.Company = "NPOI Team";
hassfworkbook.DocumentSummaryInformation = dsi;
SummaryInformation si = PropertySetFactory.CreateSummaryInformation();
si.Subject = "NPOI SDK Example";
hassfworkbook.SummaryInformation = si;
HSSFSheet sheet1 = (HSSFSheet)hassfworkbook.CreateSheet(sheetName);
HSSFRow row;
HSSFCell cell;
//写字段名
row = (HSSFRow)sheet1.CreateRow(0);
for (int i = 0; i < ds.Tables[0].Columns.Count; i++)
{
cell = (HSSFCell)row.CreateCell(i);
cell.SetCellValue(String.Format(ds.Tables[0].Columns[i].ColumnName));
}
//写记录
for (int rowIndex = 0; rowIndex < ds.Tables[0].Rows.Count; rowIndex++)
{
row = (HSSFRow)sheet1.CreateRow(rowIndex + 1);
for (int colIndex = 0; colIndex < ds.Tables[0].Columns.Count; colIndex++)
{
cell = (HSSFCell)row.CreateCell(colIndex);
cell.SetCellValue(String.Format(ds.Tables[0].Rows[rowIndex][colIndex].ToString()));
}
}
//前台调用
// HSSFWorkbook a= .DtToExcel(....)
//a.Write(Response.OutputStream)
////替换以下两句:
//hassfworkbook.Write(HttpContext.Current.Response.outputStrem);
//FileStream file = new FileStream(path + "/" + workName + ".cls", FileMode.Create);
//hassfworkbook.Write(file);
//file.Close();
return hassfworkbook;
}
}
}
里面的相关信息这里不做具体的介绍 详情请看http://tonyqus.sinaapp.com/tutorial 教程。
ExcelDoDatatable
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel; namespace TestNopi
{
public static class NPOIExcelToTable
{
private static string path = "D:\aaa.xls";
static void Main(string[] args)
{
AcquireTwoArray(ImportExcelToTable(@"path", ));
}
/// <summary>
/// 将Excel文件中的数据读出到DataTable中(xls)
/// </summary>
/// <param name="file"></param>
/// <returns></returns>
public static DataSet ImportExcelToTable(string path, int index)
{
DataSet ds = new DataSet();
DataTable dt = new DataTable();
using (FileStream fs = new FileStream(@"D:\aaa.xls", FileMode.Open, FileAccess.Read))
{
HSSFWorkbook hssfworkbook = new HSSFWorkbook(fs); ISheet sheet = hssfworkbook.GetSheetAt(index);
//表头
IRow header = sheet.GetRow(sheet.FirstRowNum);
List<int> columns = new List<int>();
for (int i = ; 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()));
}
else
dt.Columns.Add(new DataColumn(obj.ToString()));
columns.Add(i);
}
//数据
for (int i = sheet.FirstRowNum + ; 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);
}
}
ds.Tables.Add(dt);
}
return ds;
}
/// <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;
}
}
public static void AcquireTwoArray(DataSet ds)
{ foreach (DataTable dt in ds.Tables)//遍历所有的DataTable
{
foreach (DataRow dr in dt.Rows)//遍历所有的行
{
foreach (DataColumn dc in dt.Columns)//遍历所有的列
{
Console.Write("{0},{1},{2}", dt.TableName, dc.ColumnName, dr[dc].ToString());//表名,列名,单元格数据
}
} } } }
}
导入主要做到把excel转换到datatable,将datatable进行遍历即可。然后将数据插入到数据库中。如果在其中遇到什么问题,可以留言。将会尽力解答你们所遇到的问题,希望相互学习,相互提高。
如何使用NPOI 导出到excel和导入excel到数据库的更多相关文章
- .NET Core使用NPOI导出复杂,美观的Excel详解
前言: 这段时间一直专注于数据报表的开发,当然涉及到相关报表的开发数据导出肯定是一个不可避免的问题啦.客户要求要导出优雅,美观的Excel文档格式的来展示数据,当时的第一想法就是使用NPOI开源库来做 ...
- NPOI 2.1.3.1导入Excel
引入NPOI 2.1.3.1的包 项目引入 using NPOI.XSSF.UserModel;using NPOI.SS.UserModel; 控制器方法: public ActionResult ...
- 十万级百万级数据量的Excel文件导入并写入数据库
一.需求分析 最近接到一个需求,导入十万级,甚至可能百万数据量的记录了车辆黑名单的Excel文件,借此机会分析下编码过程; 首先将这个需求拆解,发现有三个比较复杂的问题: 问题一:Excel文件导入后 ...
- 批量将制定文件夹下的全部Excel文件导入微软SQL数据库
以下代码将c:\cs\文件夹下的全部Excle中数据导入到SQL数据库 declare @query vARCHAR(1000) declare @max1 int declare @count1 i ...
- Excel文件导入SQL Server数据库
Excel表格的使用可谓是非常广泛,博主也简单百度了一下Excel的发展. 发展历程: 1982年 Microsoft推出了它的第一款电子制表软件-Multiplan,并在CP/M系统上大 Excel ...
- 利用npoi把多个DataTable导入Excel多个sheet中
{ 题外拓展:把datatable插入dataset DataTable fuben = new DataTable();//定义的datatablefuben = table.Tables[0].C ...
- Winform .NET 利用NPOI导出大数据量的Excel
前言:公司让做一个导出数据到Excel的小工具,要求是用户前端输入sql语句,点击导出按钮之后,将数据导出到Excel,界面如图所示:文件下端显示导出的进度 遇到的问题: 1.使用NPOI进行Exce ...
- Npoi将excel数据导入到sqlserver数据库
/// <summary> /// 将excel导入到datatable /// </summary> /// <param name="filePath&qu ...
- jxl读取excel实现导入excel写入数据库
@RequestMapping(params = "method=import", method = RequestMethod.POST) @ResponseBody publi ...
随机推荐
- 用cython提升python的性能
Boosting performance with Cython Even with my old pc (AMD Athlon II, 3GB ram), I seldom run into ...
- sizeof()和strlen()
sizeof计算的是栈中大小 P { margin-bottom: 0.21cm; direction: ltr; color: rgb(0, 0, 0); text-align: justify } ...
- Spring + Mybatis 使用 PageHelper 插件分页
原文:http://www.cnblogs.com/yucongblog/p/5330886.html 先增加maven依赖: <dependency> <groupId>co ...
- POI导出excel的简单demo
目前使用过两种导出excel的方式,一种是如题所示的使用POI的方式进行数据的导出,这种方式一般只有在处理比较多的数据或者说需要导出的excel表格中有图片之类的需要特殊处理的文件的时候使用:还有一种 ...
- 使用mvn插件执行工程单元测试OOM的解决办法
在执行mvn test时,maven会启动一个fork进程来运行所有的单元测试类,所以我需要设置的是这个fork进程的jvm参数. 不过最终还是让我找到了http://maven.apache.org ...
- 树(一)——线段树
问题 现在有1~30这30个数,数N被抽上的概率正比于1/sqrt(N+1),求满足这个概率分布的随机数发生器. 思路 第一,如何解决这个"概率正比"问题. 第二,如何产生满足条件 ...
- Octopus系列之模板快速开发手册
公共代码 html_header_1 <title>${sitename}-${seotitle}</title> <meta http-equiv="Cont ...
- C#微信公众号接口开发实例-高级接口-申请带参数的二维码
最近公司涉及到微信绑定用户,做了高级接口-申请带参数的二维码,总结了下微信开发接口.微信接口开发都是除了消息用的xml 回复基本上都是用json的形式传递信息(post/get),开发的方法基本都是一 ...
- JavaWeb chapter 4 Servlet处理HTTP请求
1. GET/POST提交方法: 用户在网页上点击一个超链接:(get) 用户提交在网页上提交表单:(post或者get) 用户在浏览器地址栏输入URL地址并回车(get) 2. 默认情况下都是使 ...
- Five More Hacker Tools Every CISO Should Understand
As we mentioned in the first article, Top Five Hacker Tools Every CISO Should Understand, the role o ...