Excel导入到DataTable ,DataTable导入到Excel
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using NPOI.HSSF.UserModel;
using System.IO;
using System.Data;
using NPOI.SS.Util;
using NPOI.HSSF.Util;// 列 namespace Common.Utility
{
public class ExcelHelper : IDisposable
{
private string fileName = null; //文件名
private IWorkbook workbook = null;
private FileStream fs = null;
private bool disposed; public ExcelHelper(string fileName)
{
this.fileName = fileName;
disposed = false;
} /// <summary>
/// 将DataTable数据导入到excel中
/// </summary>
/// <param name="data">要导入的数据</param>
/// <param name="isColumnWritten">DataTable的列名是否要导入</param>
/// <param name="sheetName">要导入的excel的sheet的名称</param>
/// <returns>导入数据行数(包含列名那一行)</returns>
public int DataTableToExcel(DataTable data, string sheetName, bool isColumnWritten,string args="")
{
int i = 0;
int j = 0;
int count = 0;
ISheet sheet = null; fs = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite);
if (fileName.IndexOf(".xlsx") > 0) // 2007版本
workbook = new XSSFWorkbook();
else if (fileName.IndexOf(".xls") > 0) // 2003版本
workbook = new HSSFWorkbook(); try
{
if (workbook != null)
{
sheet = workbook.CreateSheet(sheetName);
}
else
{
return -1;
} if (isColumnWritten == true) //写入DataTable的列名
{
IRow row = sheet.CreateRow(0);
for (j = 0; j < data.Columns.Count; ++j)
{
row.CreateCell(j).SetCellValue(data.Columns[j].ColumnName);
}
count = 1;
}
else
{
count = 0;
} for (i = 0; i < data.Rows.Count; ++i)
{
IRow row = sheet.CreateRow(count);
for (j = 0; j < data.Columns.Count; ++j)
{
row.CreateCell(j).SetCellValue(data.Rows[i][j].ToString());
if (args == "export_code" && data.Rows[i][j].ToString()=="合计")
{ SetCellRangeAddress(sheet, i + 1, i + 1, 0, 3);
IRow row_1 = sheet.GetRow(i + 1);
ICell cell = row_1.GetCell(0);
ICellStyle cellstyle = workbook.CreateCellStyle();//设置垂直居中格式
cellstyle.VerticalAlignment = VerticalAlignment.Justify;//垂直居中
cellstyle.Alignment = HorizontalAlignment.Center;
cell.CellStyle = cellstyle; }
}
++count;
}
if (args == "export_code")
{
var oldCode = "";
int n = 0;
for (i = 0; i < data.Rows.Count; ++i)
{
var code = data.Rows[i][1];
if (oldCode == "")
{
oldCode = code.ToString();
n = i;
}
if (oldCode != code.ToString())
{ SetCellRangeAddress(sheet, n + 1, i, 1, 1);
IRow row = sheet.GetRow(n + 1);
ICell cell = row.GetCell(1);
ICellStyle cellstyle = workbook.CreateCellStyle();//设置垂直居中格式
cellstyle.VerticalAlignment = VerticalAlignment.Justify;//垂直居中
cellstyle.Alignment = HorizontalAlignment.Center;
cell.CellStyle = cellstyle; }
if (data.Rows[i][4].ToString() == "合计")
{
oldCode = "";
}
}
} workbook.Write(fs); //写入到excel
return count;
}
catch (Exception ex)
{
Console.WriteLine("Exception: " + ex.Message);
return -1;
}
} #region
/// <summary>
/// 获取单元格样式
/// </summary>
/// <param name="hssfworkbook">Excel操作类</param>
/// <param name="font">单元格字体</param>
/// <param name="fillForegroundColor">图案的颜色</param>
/// <param name="fillPattern">图案样式</param>
/// <param name="fillBackgroundColor">单元格背景</param>
/// <param name="ha">垂直对齐方式</param>
/// <param name="va">垂直对齐方式</param>
/// <returns></returns>
public static ICellStyle GetCellStyle(HSSFWorkbook hssfworkbook, HSSFColor fillBackgroundColor, HorizontalAlignment ha, VerticalAlignment va)
{
ICellStyle cellstyle = hssfworkbook.CreateCellStyle();
cellstyle.Alignment = ha;
cellstyle.VerticalAlignment = va;
if (fillBackgroundColor != null)
{
cellstyle.FillBackgroundColor = fillBackgroundColor.GetIndex();
}
return cellstyle;
}
/// <summary>
/// 合并单元格
/// </summary>
/// <param name="sheet">要合并单元格所在的sheet</param>
/// <param name="rowstart">开始行的索引</param>
/// <param name="rowend">结束行的索引</param>
/// <param name="colstart">开始列的索引</param>
/// <param name="colend">结束列的索引</param>
public static void SetCellRangeAddress(ISheet sheet, int rowstart, int rowend, int colstart, int colend)
{
CellRangeAddress cellRangeAddress = new CellRangeAddress(rowstart, rowend, colstart, colend);
sheet.AddMergedRegion(cellRangeAddress);
} #endregion /// <summary>
/// 将excel中的数据导入到DataTable中
/// </summary>
/// <param name="sheetName">excel工作薄sheet的名称</param>
/// <param name="isFirstRowColumn">第一行是否是DataTable的列名</param>
/// <returns>返回的DataTable</returns>
public DataTable ExcelToDataTable(string sheetName, bool isFirstRowColumn)
{
ISheet sheet = null;
DataTable data = new DataTable();
int startRow = 0;
try
{
fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
if (fileName.IndexOf(".xlsx") > 0) // 2007版本
workbook = new XSSFWorkbook(fs);
else if (fileName.IndexOf(".xls") > 0) // 2003版本
workbook = new HSSFWorkbook(fs); if (sheetName != null)
{
sheet = workbook.GetSheet(sheetName);
if (sheet == null) //如果没有找到指定的sheetName对应的sheet,则尝试获取第一个sheet
{
sheet = workbook.GetSheetAt(0);
}
}
else
{
sheet = workbook.GetSheetAt(0);
}
if (sheet != null)
{
IRow firstRow = sheet.GetRow(0);
int cellCount = firstRow.LastCellNum; //一行最后一个cell的编号 即总的列数 if (isFirstRowColumn)
{
for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
{
ICell cell = firstRow.GetCell(i);
if (cell != null)
{
string cellValue = cell.StringCellValue;
if (cellValue != null)
{
DataColumn column = new DataColumn(cellValue);
data.Columns.Add(column);
}
}
}
startRow = sheet.FirstRowNum + 1;
}
else
{
startRow = sheet.FirstRowNum;
} //最后一列的标号
int rowCount = sheet.LastRowNum;
ICell tempcell = null;
for (int i = startRow; i <= rowCount; ++i)
{
IRow row = sheet.GetRow(i);
if (row == null) continue; //没有数据的行默认是null DataRow dataRow = data.NewRow();
for (int j = row.FirstCellNum; j < cellCount; ++j)
{
tempcell = row.GetCell(j);
if (tempcell != null) //同理,没有数据的单元格都默认是null
{
switch (tempcell.CellType)
{
case CellType.Blank:
dataRow[j] = "";
break;
case CellType.String:
dataRow[j] = tempcell.StringCellValue;
break;
case CellType.Numeric:
dataRow[j] = tempcell.NumericCellValue;
break;
case CellType.Formula:
dataRow[j] = tempcell.NumericCellValue;
break;
default:
dataRow[j] = "";
break;
}
}
}
data.Rows.Add(dataRow);
}
} return data;
}
catch (Exception ex)
{
Console.WriteLine("Exception: " + ex.Message);
throw ex;
//return null;
}
} /// <summary>
/// 将excel中的数据导入到DataTable中,增加多个sheet的情况
/// </summary>
/// <param name="sheetName">excel工作薄sheet的名称</param>
/// <param name="isFirstRowColumn">第一行是否是DataTable的列名</param>
/// <returns>返回的DataTable</returns>
public DataTable ExcelToDataTable(int sheetIndex, bool isFirstRowColumn)
{
ISheet sheet = null;
DataTable data = new DataTable();
int startRow = 0;
try
{
fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
if (fileName.IndexOf(".xlsx") > 0) // 2007版本
workbook = new XSSFWorkbook(fs);
else if (fileName.IndexOf(".xls") > 0) // 2003版本
workbook = new HSSFWorkbook(fs); sheet = workbook.GetSheetAt(sheetIndex);
if (sheet != null)
{
IRow firstRow = sheet.GetRow(0);
int cellCount = firstRow.LastCellNum; //一行最后一个cell的编号 即总的列数
if (isFirstRowColumn)
{
for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
{
ICell cell = firstRow.GetCell(i);
if (cell != null)
{
string cellValue = cell.StringCellValue;
if (cellValue != null)
{
DataColumn column = new DataColumn(cellValue);
data.Columns.Add(column);
}
}
}
startRow = sheet.FirstRowNum + 1;
}
else
{
startRow = sheet.FirstRowNum;
} //最后一列的标号
int rowCount = sheet.LastRowNum;
ICell tempcell = null;
for (int i = startRow; i <= rowCount; ++i)
{
IRow row = sheet.GetRow(i);
if (row == null) continue; //没有数据的行默认是null DataRow dataRow = data.NewRow();
for (int j = row.FirstCellNum; j < cellCount; ++j)
{
tempcell = row.GetCell(j);
if (tempcell != null) //同理,没有数据的单元格都默认是null
{
switch (tempcell.CellType)
{
case CellType.Blank:
dataRow[j] = "";
break;
case CellType.String:
dataRow[j] = tempcell.StringCellValue;
break;
case CellType.Numeric:
dataRow[j] = tempcell.NumericCellValue;
break;
case CellType.Formula:
dataRow[j] = tempcell.NumericCellValue;
break;
default:
dataRow[j] = "";
break;
}
}
}
data.Rows.Add(dataRow);
}
} return data;
}
catch (Exception ex)
{
Console.WriteLine("Exception: " + ex.Message);
throw ex;
}
}
public DataTable ExcelToDataTable(int sheetIndex, int RowIndex, bool isFirstRowColumn)
{
ISheet sheet = null;
DataTable data = new DataTable();
int startRow = 0;
try
{
fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);
if (fileName.IndexOf(".xlsx") > 0) // 2007版本
workbook = new XSSFWorkbook(fs);
else if (fileName.IndexOf(".xls") > 0) // 2003版本
workbook = new HSSFWorkbook(fs); sheet = workbook.GetSheetAt(sheetIndex);
if (sheet != null)
{
IRow firstRow = sheet.GetRow(RowIndex);
int cellCount = firstRow.LastCellNum; //一行最后一个cell的编号 即总的列数
if (isFirstRowColumn)
{
for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
{
ICell cell = firstRow.GetCell(i);
if (cell != null)
{
string cellValue = cell.StringCellValue;
if (cellValue != null)
{
DataColumn column = new DataColumn(cellValue);
data.Columns.Add(column);
}
}
}
startRow = sheet.FirstRowNum + 1+ RowIndex;
}
else
{
startRow = sheet.FirstRowNum+ RowIndex;
} //最后一列的标号
int rowCount = sheet.LastRowNum;
ICell tempcell = null;
for (int i = startRow; i <= rowCount; ++i)
{
IRow row = sheet.GetRow(i);
if (row == null) continue; //没有数据的行默认是null DataRow dataRow = data.NewRow();
for (int j = row.FirstCellNum; j < cellCount; ++j)
{
tempcell = row.GetCell(j);
if (tempcell != null) //同理,没有数据的单元格都默认是null
{
switch (tempcell.CellType)
{
case CellType.Blank:
dataRow[j] = "";
break;
case CellType.String:
dataRow[j] = tempcell.StringCellValue;
break;
case CellType.Numeric:
dataRow[j] = tempcell.NumericCellValue;
break;
case CellType.Formula:
dataRow[j] = tempcell.NumericCellValue;
break;
default:
dataRow[j] = "";
break;
}
}
}
data.Rows.Add(dataRow);
}
} return data;
}
catch (Exception ex)
{
Console.WriteLine("Exception: " + ex.Message);
throw ex;
}
} public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
} protected virtual void Dispose(bool disposing)
{
if (!this.disposed)
{
if (disposing)
{
if (fs != null)
fs.Close();
} fs = null;
disposed = true;
}
}
}
}
Excel导入到DataTable ,DataTable导入到Excel的更多相关文章
- 【C#常用方法】2.DataTable(或DataSet)与Excel文件之间的导出与导入(使用NPOI)
DataTable与Excel之间的互导 1.项目添加NPOI的引用 NPOI项目简介: NPOI是一个开源的C#读写Excel.WORD等微软OLE2组件文档的项目,特点是可以在没有安装Office ...
- .net实现与excel的数据交互、导入导出
应该说,一套成熟的基于web的管理系统,与用户做好的excel表格进行数据交互是一个不可或缺的功能,毕竟,一切以方便客(jin)户(qian)为宗旨. 本人之前从事PHP的开发工作,熟悉PHP的都应该 ...
- .Net MVC 导入导出Excel总结(三种导出Excel方法,一种导入Excel方法) 通过MVC控制器导出导入Excel文件(可用于java SSH架构)
.Net MVC 导入导出Excel总结(三种导出Excel方法,一种导入Excel方法) [原文地址] 通过MVC控制器导出导入Excel文件(可用于java SSH架构) public cl ...
- Excel大数据量分段导入到Oracle
客户需要将一个具有2W多条数据的Excel表格中的数据导入到Oracle数据库的A表中,开始采用的是利用Oledb直接将数据读入到DataTable中,然后通过拼接InserInto语句来插入到数据库 ...
- C#调用NPOI组件读取excel表格数据转为datatable写入word表格中并向word中插入图片/文字/书签 获得书签列表
调用word的com组件将400条数据导入word表格中耗时10分钟简直不能忍受,使用NPOI组件耗时4秒钟.但是NPOI中替换书签内容的功能不知道是不支持还是没找到. 辅助类 Excel表格数据与D ...
- Excel导入导出,生成和下载Excel报表、附件等操作--ASP.NET
public class OutExcel { public static void OutExcel_bb(DataTable dt, string thepath, string temppath ...
- 使用OpenXML将Excel内容读取到DataTable中
前言:前面的几篇文章简单的介绍了如何使用OpenXML创建Excel文档.由于在平时的工作中需要经常使用到Excel的读写操作,简单的介绍下使用 OpenXML读取Excel中得数据.当然使用Open ...
- .Net之Nopi Excel数据导出和批量导入功能
一.介绍NPOI和编写demo的原因 1.Npoi是什么: 它是一个专门用于读写Microsoft Office二进制和OOXML文件格式的.NET库,我们使用它能够轻松的实现对应数据的导入,导出功能 ...
- DataTable数据导出到Excel,并发送到客户端进行下载
本代码实现思路是:页面显示和导出分开,导出的数据和用于页面显示的是同一查询数据方式,所以也是同样的数据,只是在导出数据时从数据库重新捞了一次数据.此导出数据方式会先将数据保存到Excel中,然后将创建 ...
- datatable导出到Word / Excel / PDF / HTML .NET
原文发布时间为:2011-01-21 -- 来源于本人的百度文章 [由搬家工具导入] IEnumerable - DataTable Export to Word / Excel / PDF / HT ...
随机推荐
- Win10 UWP Tile Generator
图标生成器 https://marketplace.visualstudio.com/items?itemName=shenchauhan.UWPTileGenerator 备份地址: http:// ...
- CorelDRAW X8超低价优惠啦,你却还在用CDR X4破解?!
最近大火的<都挺好> 已经完美收官 出于好奇,小编也正在追剧呢 同样出生在畸形的原生家庭 长大后 有钱就是苏明玉 没钱就是樊胜美 所以不要抱怨老天给了你怎样的资源 想要什么就要靠自己的双手 ...
- Java中 ArrayList类常用方法和遍历
ArrayList类对于元素的操作,基本体现在——增.删.查.常用的方法有: public boolean add(E e) :将指定的元素添加到此集合的尾部. public E remove(in ...
- JS 从36个数字里面随机抽取8个
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title> ...
- 【LeetCode算法】LeetCode初级算法——字符串
在LeetCode初级算法的字符串专题中,共给出了九道题目,分别为:反转字符串,整数反转,字符串中的第一个唯一字符,有效的字母异位词,验证回文字符串,字符串转换整数,实现strStr(),报数,最 ...
- 训练1-W
有一个长度为n(n<=100)的数列,该数列定义为从2开始的递增有序偶数,现在要求你按照顺序每m个数求出一个平均值,如果最后不足m个,则以实际数量求平均值.编程输出该平均值序列. Input 输 ...
- django rest-farme-work 的使用(3)
请求和响应 Requests and Responses 从这一片来说,我们将真正开始覆盖REST框架的核心.我们来介绍一些基本的构建块 Request objects REST框架引入了一个Requ ...
- Spring 使用外部属性文件配置
1.Spring提供了一个PropertyPlaceholderConfigurer的BeanFactory后置处理器,这个处理器允许用户将Bean的配置的部分内容 移到属性文件中.可以在Bean配置 ...
- Python 使用matplotlib模块模拟掷骰子
掷骰子 骰子类 # die.py 骰子类模块 from random import randint class Die(): """骰子类""&quo ...
- 关于高校表白APP的用户模板和用户场景
用户模板一: 用户名 小明 性别,年龄 男,20岁 用户状况 单身,在校大学生 生活爱好 喜欢打篮球,唱歌 典型场景 希望找到一个心仪的可以走到最后的姑娘 典型描述 交友 用户比例 ? 用户场景一 ...