/// <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表格文件当中,导出/导入数据的更多相关文章

  1. Java导出数据行写入到Excel表格:基于Apache POI

    Java导出数据行写入到Excel表格:基于Apache POI import java.io.File; import java.io.FileOutputStream; import org.ap ...

  2. Java POI读取Excel数据,将数据写入到Excel表格

    1.准备 首先需要导入poi相应的jar包,包括: 下载地址:http://pan.baidu.com/s/1bpoxdz5 所需要的包的所在位置包括: 2.读取Excel数据代码 package S ...

  3. php中读写excel表格文件示例。

    测试环境:php5.6.24.这块没啥兼容问题. 需要更多栗子,请看PHPExcel的examples.还是蛮强大的. 读取excel文件. 第一步.下载开源的PHPExcel的类库文件,官方网站是h ...

  4. pyhton读取 excel表格文件

    2019的第一天,忘记昨日之事,迎接新的明天. excel表格文件办公中常用,如通过Python操作这些数据需导入并有序读取这些数据 特随笔,供以后查阅 代码如下: import xlrd # fil ...

  5. python读取Excel表格文件

    python读取Excel表格文件,例如获取这个文件的数据 python读取Excel表格文件,需要如下步骤: 1.安装Excel读取数据的库-----xlrd 直接pip install xlrd安 ...

  6. GreenPlum/postgres copy命令导出/导入数据

    一.COPY命令简单实用 1.copy在postgres与GreenPlum介绍 1.1 postgrespostgres的COPY命令可以快速的导出/导入数据到postgresql数据库中,支持常用 ...

  7. PHP生成excel表格文件并下载

    本文引自网络,仅供自己学习之用. 利用php导出excel我们大多会直接生成.xls文件,这种方便快捷. function createtable($list,$filename){ header(& ...

  8. python操作excel表格文件--使用xlrd模块

    原文: http://www.cnblogs.com/lhj588/archive/2012/01/06/2314181.html 引言: 实际工作中,可能很多情况下都会用到excel表格,像如果不需 ...

  9. 在网页中预览excel表格文件

    项目需求在前端页面中实现预览excel表格的功能,上网了解之后大致总结为一下几种方法. 1.office文档转换为pdf,再转swf,然后通过网页加载flash进行预览 2.通过 xlsx.js,js ...

  10. Python 处理 CSV/EXCEL 表格文件

    只想说,数据挖掘工作,80%时间都花在处理数据上了,这句话真不假! 最近和小伙伴组了个队参加数据分析比赛,记录下我处理 csv 文件的一些步骤吧: 修改csv文件 可以用csv模块1,官方文档2 im ...

随机推荐

  1. JZOJ 2020.07.30【NOIP提高组】模拟

    总结 本场比赛很不负责对待 暴力都没怎么打 一个半小时后才开始打题 很悲剧的只有 \(23+11+36=70\) 分 \(T1\) 4300. 装饰大楼 题目 略 思路 很无聊的找规律题 考场弃疗 \ ...

  2. 前后端分离项目创建项目详细过程项、目需求分析、pip换源、创建虚环境、后端目录调整以及解决问题

    引言,本项目是前后端分离的,前端用Vue2 后端用Django,后台管理部分是通过simpleUI完成的项目,项目名称为路飞,是商城类(知识付费项目).本篇文章主要讨论一个前后端分离的项目第一步怎么做 ...

  3. Postgresql CTE解析

    一.简介 WITH提供了一种方式来书写在一个大型查询中使用的辅助语句.这些语句通常被称为公共表表达式或CTE(Common Table Expressions),它们可以被看成是定义只在一个查询中存在 ...

  4. ve-plus:基于 vue3.x 桌面端UI组件库|vue3组件库

    VE-Plus 自研轻量级 vue3.js 桌面pc端UI组件库 经过一个多月的筹划及开发,今天给大家带来一款全新的Vue3桌面端UI组件库VEPlus.新增了35+常用的组件,采用vue3 setu ...

  5. zint

    一.Zint1. 介绍 Zint是一个软件,允许在任何广泛的公共领域条形码标准中轻松编码数据,并允许将这种功能集成到您自己的程序中. Zint项目的目标是提供一个完全跨平台的开源条形码生成解决方案,目 ...

  6. 前端js下载excel

    // 1.文件流下载文件: export function axiosPostExport(url, data, fileName, suffix = '.xlsx') {     url = get ...

  7. Kubernetes 网络模型基础指南

    Kubernetes 是为运行分布式集群而建立的,分布式系统的本质使得网络成为 Kubernetes 的核心和必要组成部分,了解 Kubernetes 网络模型可以使你能够正确运行.监控和排查应用程序 ...

  8. 【狂神说】SpringMVC笔记

    1.回顾MVC ssm:mybatis+Spring+SpringMVC MVC三层架构 ssm框架:研究官方文档,锻炼自学能力,锻炼项目能力 SpringMVC+Vue+SpringBoot+Spr ...

  9. Linux 磁盘扩容

    原文链接:https://blog.csdn.net/zzq100zzq/article/details/125178843 一.查看系统磁盘1.使用df -hl ,查看系统的磁盘使用情况二.linu ...

  10. Windows 从头搭建c++ Eigen 库

    虽然目前还在用python实现自己的算法,但是还是有点略微不满足,算法迟早有一天全从python搬到c++上,先给自己立个flag. 前言 由于本人做一些模型的搭建和计算,矩阵运算必然是少不了的,本人 ...