写入到Excel表格文件当中,导出/导入数据
/// <summary>
/// 写入到Excel表格文件当中,导出数据
/// </summary>
/// <param name="dt"></param>
/// <returns></returns>
public bool DataTableToExcel(DataTable dt, string DataFile)
{
bool result = false;
IWorkbook workbook = null;
FileStream fs = null;
IRow row = null;
ISheet sheet = null;
ICell cell = null;
try
{
if (dt != null && dt.Rows.Count > 0)
{
workbook = new HSSFWorkbook();
string NowBOPName = this.CmbBOPName.Text.Trim();
sheet = workbook.CreateSheet(NowBOPName);//创建一个名称为Sheet0的表
int rowCount = dt.Rows.Count;//行数
int columnCount = dt.Columns.Count;//列数 //把A0:C0合并为一个单元格 并赋值
ICell hbcell = sheet.CreateRow(0).CreateCell(0);
hbcell.SetCellValue(NowBOPName + "工序");
sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(0, 0, 0, 2)); //设置样式 居中 字体
ICellStyle hbstyle = workbook.CreateCellStyle();
hbstyle.VerticalAlignment = VerticalAlignment.Center;
hbstyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
IFont hbfont = workbook.CreateFont();
hbfont.FontHeight = 15 * 20;
hbstyle.SetFont(hbfont);
hbcell.CellStyle = hbstyle; //设置列头
row = sheet.CreateRow(1);//excel第一行设为标题,第二行列头
for (int c = 0; c < columnCount; c++)
{
cell = row.CreateCell(c);
cell.SetCellValue(dt.Columns[c].ColumnName);
} //设置每行每列的单元格,
for (int i = 0; i < rowCount; i++)
{
row = sheet.CreateRow(i + 2);//excel第三行开始写入数据
for (int j = 0; j < columnCount; j++)
{
cell = row.CreateCell(j);
cell.SetCellValue(dt.Rows[i][j].ToString());
}
}
using (fs = File.OpenWrite(DataFile))
{
workbook.Write(fs);//向打开的这个xls文件中写入数据
result = true;
}
}
return result;
}
catch (Exception ex)
{
if (fs != null)
{
fs.Close();
}
return false;
}
}
/// <summary>
/// 将excel导入到datatable
/// </summary>
/// <param name="filePath">excel路径</param>
/// <param name="isColumnName">第一行是否是列名</param>
/// <returns>返回datatable</returns>
public static DataTable ExcelToDataTable(string filePath, bool isColumnName)
{
DataTable dataTable = null;
FileStream fs = null;
DataColumn column = null;
DataRow dataRow = null;
IWorkbook workbook = null;
ISheet sheet = null;
IRow row = null;
ICell cell = null;
int startRow = 0;
try
{
using (fs = File.OpenRead(filePath))
{
// 2007版本
if (filePath.IndexOf(".xlsx") > 0)
workbook = new XSSFWorkbook(fs);
// 2003版本
else if (filePath.IndexOf(".xls") > 0)
workbook = new HSSFWorkbook(fs); if (workbook != null)
{ sheet = workbook.GetSheetAt(0);//读取第一个sheet,当然也可以循环读取每个sheet dataTable = new DataTable();
if (sheet != null)
{
int rowCount = sheet.LastRowNum;//总行数
if (rowCount > 0)
{
IRow firstRow = sheet.GetRow(1);//第二行列名
int cellCount = firstRow.LastCellNum;//列数 //构建datatable的列
if (isColumnName)
{
startRow = 2;//如果第一行是标题,第二行列名,则从第二行开始读取
for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
{
cell = firstRow.GetCell(i);
if (cell != null)
{
if (cell.StringCellValue != null)
{
column = new DataColumn(cell.StringCellValue);
dataTable.Columns.Add(column);
}
}
}
}
else
{
for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
{
column = new DataColumn("column" + (i + 1));
dataTable.Columns.Add(column);
}
} //填充行
for (int i = startRow; i <= rowCount; ++i)
{
row = sheet.GetRow(i);
if (row == null) continue; dataRow = dataTable.NewRow();
for (int j = row.FirstCellNum; j < cellCount; ++j)//dataTable.Columns.Count
{
cell = row.GetCell(j);
if (cell == null)
{
dataRow[j] = "";
}
else
{
//CellType(Unknown = -1,Numeric = 0,String = 1,Formula = 2,Blank = 3,Boolean = 4,Error = 5,)
switch (cell.CellType)
{
case CellType.Blank:
dataRow[j - row.FirstCellNum] = "";
break;
case CellType.Numeric:
short format = cell.CellStyle.DataFormat;
//对时间格式(2015.12.5、2015/12/5、2015-12-5等)的处理
if (format == 14 || format == 31 || format == 57 || format == 58)
dataRow[j - row.FirstCellNum] = cell.DateCellValue;
else
dataRow[j - row.FirstCellNum] = cell.NumericCellValue;
break;
case CellType.String:
dataRow[j - row.FirstCellNum] = cell.StringCellValue;
break;
case CellType.Formula:
//System.Globalization.NumberFormatInfo nfi = new System.Globalization.NumberFormatInfo();
//nfi.NumberDecimalDigits = 2;
//short format = cell.CellStyle.Format("{0:F2}", Convert.ToDouble(23, 5235);
dataRow[j - row.FirstCellNum] = ((float)cell.NumericCellValue);
break;
}
}
}
dataTable.Rows.Add(dataRow);
}
}
}
}
}
return dataTable;
}
catch (Exception ex)
{ if (fs != null)
{
fs.Close();
}
return null;
}
}
写入到Excel表格文件当中,导出/导入数据的更多相关文章
- Java导出数据行写入到Excel表格:基于Apache POI
Java导出数据行写入到Excel表格:基于Apache POI import java.io.File; import java.io.FileOutputStream; import org.ap ...
- Java POI读取Excel数据,将数据写入到Excel表格
1.准备 首先需要导入poi相应的jar包,包括: 下载地址:http://pan.baidu.com/s/1bpoxdz5 所需要的包的所在位置包括: 2.读取Excel数据代码 package S ...
- php中读写excel表格文件示例。
测试环境:php5.6.24.这块没啥兼容问题. 需要更多栗子,请看PHPExcel的examples.还是蛮强大的. 读取excel文件. 第一步.下载开源的PHPExcel的类库文件,官方网站是h ...
- pyhton读取 excel表格文件
2019的第一天,忘记昨日之事,迎接新的明天. excel表格文件办公中常用,如通过Python操作这些数据需导入并有序读取这些数据 特随笔,供以后查阅 代码如下: import xlrd # fil ...
- python读取Excel表格文件
python读取Excel表格文件,例如获取这个文件的数据 python读取Excel表格文件,需要如下步骤: 1.安装Excel读取数据的库-----xlrd 直接pip install xlrd安 ...
- GreenPlum/postgres copy命令导出/导入数据
一.COPY命令简单实用 1.copy在postgres与GreenPlum介绍 1.1 postgrespostgres的COPY命令可以快速的导出/导入数据到postgresql数据库中,支持常用 ...
- PHP生成excel表格文件并下载
本文引自网络,仅供自己学习之用. 利用php导出excel我们大多会直接生成.xls文件,这种方便快捷. function createtable($list,$filename){ header(& ...
- python操作excel表格文件--使用xlrd模块
原文: http://www.cnblogs.com/lhj588/archive/2012/01/06/2314181.html 引言: 实际工作中,可能很多情况下都会用到excel表格,像如果不需 ...
- 在网页中预览excel表格文件
项目需求在前端页面中实现预览excel表格的功能,上网了解之后大致总结为一下几种方法. 1.office文档转换为pdf,再转swf,然后通过网页加载flash进行预览 2.通过 xlsx.js,js ...
- Python 处理 CSV/EXCEL 表格文件
只想说,数据挖掘工作,80%时间都花在处理数据上了,这句话真不假! 最近和小伙伴组了个队参加数据分析比赛,记录下我处理 csv 文件的一些步骤吧: 修改csv文件 可以用csv模块1,官方文档2 im ...
随机推荐
- nvm管理node和npm
安装nvm 下载地址:https://github.com/coreybutler/nvm-windows/releases 下载前卸载调node,安装时注意记住所在路径,傻瓜式安装.安装后nvm - ...
- 欧拉函数和遗忘自动机 SX 的故逝
欧拉函数 \(\varphi(n)\) 定义为小于 \(n\) 与 \(n\) 互质的数字,炒个例子,\(\varphi(10) = 4\),因为 \(1,3,7,9\) 与 \(10\) 互质. 怎 ...
- 跳板攻击之:lcx 端口转发
跳板攻击之:lcx 端口转发 郑重声明: 本笔记编写目的只用于安全知识提升,并与更多人共享安全知识,切勿使用笔记中的技术进行违法活动,利用笔记中的技术造成的后果与作者本人无关.倡导维护网络安全人人有责 ...
- js(最新)手机号码 正则验证 - 代码篇
现在手机号码,除了以11+.12+开头的没有,别的好像都有了! 代码如下: 方法一: function checkPhone(){ var phone = $(".phone"). ...
- 单一资产VAR风险--基于python
数据源:使用 AKShare包.它是一个免费.开源的 Python 财经数据接口包.网址https://www.akshare.xyz/index.html 一.获取数据: 计算日收益率: impor ...
- z order curve
https://www.cnblogs.com/tgzhu/p/8286616.html
- centos7 安装MariaDB数据库
1.添加 MariaDB yum源 #添加MariaDB.repo配置文件 vim /etc/yum.repos.d/MariaDB.repo #添加内容 [mariadb] name = Maria ...
- 【Redis的三种数据删除策略】定时定期惰性,超出内存就自动清理
https://blog.csdn.net/DQWERww/article/details/126453008 https://blog.csdn.net/qq_38056518/article/de ...
- vue项目中禁用浏览器缓存配置案例
项目发布新版本,部署线上后用户浏览器需要清理缓存 1.public文件夹中修改 index.html文件meta配置 <meta http-equiv="Cache-Control&q ...
- R包本地安装方法
问题 需要安装一个R的测试包 但是这个包没有在cran中 也没有在biomanager中 于是决定使用devtools-github安装 遇到问题 无法下载github上的R包 策略 使用local方 ...