using System;
using System.Collections.Generic;
using NPOI;
using NPOI.HPSF;
using NPOI.HSSF;
using NPOI.HSSF.UserModel;
using NPOI.POIFS;
using NPOI.Util;
using System.Text;
using System.IO;
using System.Data;
using System.Data.OleDb;
using NPOI.SS.UserModel; namespace Business
{
public class CExcelOut
{
/// <summary>导出EXCEL表</summary>
/// <param name="table">table表</param>
/// <returns>二进制流</returns>
public MemoryStream GetExecOut(DataTable table)
{
if (table == null)
{
return null;
}
List<DataTable> listTable = new List<DataTable>();
listTable.Add(table);
return GetExecOut(listTable);
}
/// <summary>导入多个EXCEL表</summary>
/// <param name="listTable">表集合</param>
/// <returns>二进制流</returns>
public MemoryStream GetExecOut(List<DataTable> listTable)
{
try
{
if (listTable == null || listTable.Count == )
{
return null;
}
Dictionary<string, DataTable> rowTable = new Dictionary<string, DataTable>();
for (int i = ; i < listTable.Count; i++)
{
rowTable.Add("sheet" + (i + ), listTable[i]);
}
return GetExecOut(rowTable);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return null;
}
}
/// <summary>导入多个EXCEL表 键是表名 值是table表</summary>
/// <param name="listTable">键值对集合</param>
/// <returns>二进制流</returns>
public MemoryStream GetExecOut(Dictionary<string, DataTable> listTable)
{
if (listTable == null || listTable.Count == )
{
return null;
}
HSSFWorkbook workbook = new HSSFWorkbook();
MemoryStream ms = new MemoryStream();
try
{
foreach (KeyValuePair<string, DataTable> item in listTable)
{
string steerName = item.Key;
//文件名
NPOI.SS.UserModel.ISheet sheet = workbook.CreateSheet(steerName);
//头部
NPOI.SS.UserModel.IRow headerRow = sheet.CreateRow();
foreach (DataColumn itemColumn in item.Value.Columns)
{
headerRow.CreateCell(itemColumn.Ordinal).SetCellValue(itemColumn.ColumnName);
}
int rowIndex = ;
foreach (DataRow itemRow in item.Value.Rows)
{
NPOI.SS.UserModel.IRow dataRow = sheet.CreateRow(rowIndex);
foreach (DataColumn itemColumn in item.Value.Columns)
{
dataRow.CreateCell(itemColumn.Ordinal).
SetCellValue(itemRow[itemColumn.ColumnName].ToString());
}
rowIndex++;
}
}
workbook.Write(ms);
ms.Flush();
ms.Position = ;
return ms; }
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return null;
}
finally
{
workbook = null;
}
}
/// <summary>把流转换为文件</summary>
/// <param name="PathUrl">文件路径,如果文件存在则覆盖,不存在创建</param>
/// <param name="ms">IO流</param>
public void ExeclOut(string PathUrl, Stream ms)
{
try
{
if (PathUrl.Length == || ms == null)
{
return;
}
FileStream file = new FileStream(PathUrl, FileMode.Create);
if (ms.CanRead)
{
int lentgth = ;
byte[] by = new byte[lentgth];
lentgth = ms.Read(by, , lentgth);
while (lentgth != )
{
file.Write(by, , lentgth);
lentgth = ms.Read(by, , lentgth);
}
file.Close();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
} /// <summary>Excel表变成dataTable</summary>
/// <param name="filePath">Excel表格路径</param>
/// <param name="sheetName">查询表名</param>
/// <returns>数据集合</returns>
public DataTable GetTop1ExcelData(string filePath, string sheetName)
{
DataSet ds = new DataSet();
try
{ string connectionString = "provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended properties=Excel 8.0;";
string sql = "select * from [" + sheetName + "$]";
using (OleDbConnection con = new OleDbConnection(connectionString))
{
OleDbCommand cmd = new OleDbCommand(sql, con);
OleDbDataAdapter adapt = new OleDbDataAdapter(cmd);
adapt.Fill(ds);
if (ds != null && ds.Tables.Count > )
{
return ds.Tables[];
}
return null;
}
}
catch (Exception exp)
{
Console.WriteLine(exp.Message);
return null;
}
} /// <summary>Excel表变成dataTable</summary>
/// <param name="filePath">Excel表格路径</param>
/// <param name="sheetName">查询表名</param>
/// <returns>数据集合</returns>
public DataTable GetExcelData(string filePath, string sheetName)
{
DataSet ds = new DataSet();
try
{
string connectionString = "provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended properties='Excel 8.0;HDR=NO;IMEX=1'";
string sql = "select * from [" + sheetName + "$]";
using (OleDbConnection con = new OleDbConnection(connectionString))
{
OleDbCommand cmd = new OleDbCommand(sql, con);
OleDbDataAdapter adapt = new OleDbDataAdapter(cmd);
adapt.Fill(ds);
if (ds != null && ds.Tables.Count > )
{
return ds.Tables[];
}
return null;
}
}
catch (Exception exp)
{
Console.WriteLine(exp.Message);
return null;
}
}
/// <summary>
/// Excel表变成dataTable
/// </summary>
/// <param name="filePath">Excel表格路径</param>
/// <returns>数据集合</returns>
public DataTable GetExcelData(string filePath)
{
DataTable table = new DataTable();
try
{
FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
HSSFWorkbook hssfWorkbook = new HSSFWorkbook(fileStream); ISheet iSheet = hssfWorkbook.GetSheetAt();
if (iSheet != null)
{
IRow iRow = iSheet.GetRow();
int cellCount = iRow.LastCellNum; for (int i = iRow.FirstCellNum; i < cellCount; i++)
{
DataColumn column = new DataColumn(iRow.GetCell(i).StringCellValue);
table.Columns.Add(column);
} int rowCount = iSheet.LastRowNum;
for (int i = (iSheet.FirstRowNum + ); i < iSheet.LastRowNum; i++)
{
IRow row = iSheet.GetRow(i);
DataRow dataRow = table.NewRow(); for (int j = row.FirstCellNum; j < cellCount; j++)
{
if (row.GetCell(j) != null)
{
dataRow[j] = row.GetCell(j).ToString();
}
} table.Rows.Add(dataRow);
}
} fileStream.Flush();
fileStream.Dispose();
fileStream.Close();
fileStream = null; hssfWorkbook.Dispose();
hssfWorkbook = null;
iSheet.Dispose();
iSheet = null;
}
catch (Exception exp)
{ }
finally
{
}
return table;
}
/// <summary>
/// App设置导出Excel模板
/// </summary>
/// <param name="tbData"></param>
/// <param name="headTb"></param>
/// <param name="steerName"></param>
/// <returns></returns>
public MemoryStream GetExecOut(DataTable tbData, DataTable headTb, string steerName)
{
if (tbData == null || tbData.Rows.Count == )
{
return null;
}
HSSFWorkbook workbook = new HSSFWorkbook();
MemoryStream ms = new MemoryStream();
try
{
//文件名
NPOI.SS.UserModel.ISheet sheet = workbook.CreateSheet(steerName);
ICellStyle style = GetStyle(workbook);
ICellStyle styleLeft = GetStyle(workbook, HorizontalAlignment.LEFT);
ICellStyle styleSize = GetStyle(workbook, ); int rowIndex = ;
//头部
NPOI.SS.UserModel.IRow headerRow = sheet.CreateRow(rowIndex);
ICell cell = headerRow.CreateCell(, CellType.STRING);
cell.SetCellValue("分层标电子水准测量记录手簿");
cell.CellStyle = style;
sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(rowIndex, rowIndex, , ));
//设置单元格的高度实际是设置其所在行高,所以要在单元格所在行上设置行高,行高设置数值好像是像素点的1/20,所以*20以便达到设置效果;
//设置单元格的宽度实际上是设置其所在列宽,所以要在单元格所在列上设置(列的设置在工作表上),宽度数值好像是字符的1/256,所以*256以便达到设置效果。
for (int i = ; i < ; i++)
{
sheet.SetColumnWidth(i, * );
}
headerRow.Height = * ;
rowIndex++;
foreach (DataRow itemRow in headTb.Rows)
{
headerRow = sheet.CreateRow(rowIndex);
cell = headerRow.CreateCell(, CellType.STRING);
cell.SetCellValue(itemRow["Columns1"].ToString());
cell.CellStyle = style; cell = headerRow.CreateCell(, CellType.STRING);
cell.SetCellValue(itemRow["Columns2"].ToString());
cell.CellStyle = styleLeft; cell = headerRow.CreateCell(, CellType.STRING);
cell.CellStyle = style; cell = headerRow.CreateCell(, CellType.STRING);
cell.CellStyle = style; cell = headerRow.CreateCell(, CellType.STRING);
cell.SetCellValue(itemRow["Columns3"].ToString());
cell.CellStyle = style; cell = headerRow.CreateCell(, CellType.STRING);
cell.SetCellValue(itemRow["Columns4"].ToString());
cell.CellStyle = styleLeft; cell = headerRow.CreateCell(, CellType.STRING);
cell.CellStyle = style; cell = headerRow.CreateCell(, CellType.STRING);
cell.CellStyle = style; headerRow.Height = * ;
//跨行 跨列 起始行 终止行 起始列 终止列
sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(rowIndex, rowIndex, , ));
sheet.AddMergedRegion(new NPOI.SS.Util.CellRangeAddress(rowIndex, rowIndex, , ));
rowIndex++;
}
NPOI.SS.UserModel.IRow dataRow = sheet.CreateRow(rowIndex);
dataRow.Height = * ;
sheet.SetColumnWidth(rowIndex, * );
cell = dataRow.CreateCell(, CellType.STRING);
cell.SetCellValue("测回编号");
cell.CellStyle = styleSize; cell = dataRow.CreateCell(, CellType.STRING);
cell.SetCellValue("标点编号");
cell.CellStyle = styleSize; cell = dataRow.CreateCell(, CellType.STRING);
cell.SetCellValue("中丝读数1");
cell.CellStyle = styleSize; cell = dataRow.CreateCell(, CellType.STRING);
cell.SetCellValue("中丝读数2");
cell.CellStyle = styleSize; cell = dataRow.CreateCell(, CellType.STRING);
cell.SetCellValue("中丝读数3");
cell.CellStyle = styleSize; cell = dataRow.CreateCell(, CellType.STRING);
cell.SetCellValue("距离");
cell.CellStyle = styleSize; cell = dataRow.CreateCell(, CellType.STRING);
cell.SetCellValue("中丝读数均值");
cell.CellStyle = styleSize; cell = dataRow.CreateCell(, CellType.STRING);
cell.SetCellValue("高差");
cell.CellStyle = styleSize; rowIndex++;
foreach (DataRow itemRow in tbData.Rows)
{
dataRow = sheet.CreateRow(rowIndex);
dataRow.Height = * ;
foreach (DataColumn itemColumn in tbData.Columns)
{
dataRow.CreateCell(itemColumn.Ordinal, CellType.STRING).SetCellValue(itemRow[itemColumn.ColumnName].ToString());
dataRow.Cells[itemColumn.Ordinal].CellStyle = styleSize;
}
rowIndex++;
}
workbook.Write(ms);
ms.Flush();
ms.Position = ;
return ms; }
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return null;
}
finally
{
workbook = null;
}
}
/// <summary>
/// App原始中间报表导出模板
/// </summary>
/// <param name="tbData"></param>
/// <returns></returns>
public MemoryStream GetExcelOut(DataTable tbData)
{
if (tbData == null || tbData.Rows.Count == )
{
return null;
}
HSSFWorkbook workbook = new HSSFWorkbook();
MemoryStream ms = new MemoryStream();
try
{
//文件名
NPOI.SS.UserModel.ISheet sheet = workbook.CreateSheet("Sheet1");
ICellStyle style = GetStyle(workbook);
ICellStyle styleSize = GetStyle(workbook, ); int rowIndex = ;
//头部
NPOI.SS.UserModel.IRow headerRow = sheet.CreateRow(rowIndex);
//设置单元格的高度实际是设置其所在行高,所以要在单元格所在行上设置行高,行高设置数值好像是像素点的1/20,所以*20以便达到设置效果;
//设置单元格的宽度实际上是设置其所在列宽,所以要在单元格所在列上设置(列的设置在工作表上),宽度数值好像是字符的1/256,所以*256以便达到设置效果。
headerRow.Height = * ;
foreach (DataColumn itemColumn in tbData.Columns)
{
ICell cell = headerRow.CreateCell(itemColumn.Ordinal, CellType.STRING);
cell.SetCellValue(itemColumn.ColumnName);
cell.CellStyle = style;
//设置列宽度
sheet.SetColumnWidth(itemColumn.Ordinal, * );
} rowIndex++;
foreach (DataRow itemRow in tbData.Rows)
{
IRow dataRow = sheet.CreateRow(rowIndex);
dataRow.Height = * ;
foreach (DataColumn itemColumn in tbData.Columns)
{
dataRow.CreateCell(itemColumn.Ordinal, CellType.STRING).SetCellValue(itemRow[itemColumn.ColumnName].ToString());
dataRow.Cells[itemColumn.Ordinal].CellStyle = styleSize;
}
rowIndex++;
}
workbook.Write(ms);
ms.Flush();
ms.Position = ;
return ms; }
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return null;
}
finally
{
workbook = null;
}
}
/// <summary>
/// 获取默认样式
/// </summary>
/// <param name="workbook"></param>
/// <returns></returns>
public ICellStyle GetStyle(HSSFWorkbook workbook)
{
return GetStyle(workbook, , HorizontalAlignment.CENTER_SELECTION);
}
/// <summary>
/// 获取样式
/// </summary>
/// <param name="workbook"></param>
/// <param name="size">设置字体大小</param>
/// <returns></returns>
public ICellStyle GetStyle(HSSFWorkbook workbook, short size)
{
return GetStyle(workbook, size, HorizontalAlignment.CENTER_SELECTION);
}
/// <summary>
/// 获取样式
/// </summary>
/// <param name="workbook"></param>
/// <param name="ali">设置文本居中</param>
/// <returns></returns>
public ICellStyle GetStyle(HSSFWorkbook workbook, HorizontalAlignment ali)
{
return GetStyle(workbook, , ali);
}
/// <summary>
/// 获取样式
/// </summary>
/// <param name="workbook"></param>
/// <param name="size">设置字体大小</param>
/// <param name="ali">设置文本居中</param>
/// <returns></returns>
public ICellStyle GetStyle(HSSFWorkbook workbook, short size, HorizontalAlignment ali)
{
try
{
ICellStyle style = workbook.CreateCellStyle();
//居中
style.VerticalAlignment = VerticalAlignment.CENTER;
//水平居中
style.Alignment = ali;
//设置字体
IFont font = workbook.CreateFont();
font.FontName = "微软雅黑";
//设置大小
font.FontHeightInPoints = size;
style.SetFont(font);
return style;
}
catch (Exception ex)
{
return null;
}
} }
}

NPOI.DLL下载地址 http://files.cnblogs.com/files/changeMe/NPOI.zip

C#Excel导出导入的更多相关文章

  1. 使用NPOI组件完成的Excel导出导入(附源代码,测试通过)

    最近遇到一个Excel导入导出的问题,要支持winform和webform,这里我是一个认真严谨的coder,所以决定把这个记录下来!和大家一起分享一下!如果需要的同学可以下载哦! 对于NPOI这个组 ...

  2. excel导出导入通用方法

    /** * 方法说明:批量导出通用方法 * 创建时间:2018年8月24日 *** * @param filePath 文件地址 * @param sheetName 分页名称 * @param ti ...

  3. excel 导出导入

    /** * 导出 * @param * @param * @return */ public function exportexcel() { set_time_limit(0); ini_set(' ...

  4. php 之 excel导出导入合并

    <?php class Excel extends Controller { //直属高校 public function __construct() { parent::Controller( ...

  5. php做EXCEL数据导出导入开发的一些小问题

    前两天刚刚做开发CRM系统项目,在做要做EXCEL导出导入功能,因为以前做.NET开发用的是NPOI,但可是没找到PHP版本的,所以就网搜找了个国外的开源PHPEXCEL , 一开始只是做了简单的导入 ...

  6. java利用EasyPoi实现Excel导出功能

    easypoi功能如同名字easy,主打的功能就是容易,让一个没见接触过poi的人员 就可以方便的写出Excel导出,Excel模板导出,Excel导入,Word模板导出,通过简单的注解和模板 语言( ...

  7. [moka同学笔记]PHPexcel之excel导出和导入

    原案例来自http://www.sucaihuo.com/有修改 1.目录结构(文件不用解释,应该都可以看得懂,直接看代码)

  8. excel的导入导出的实现

    1.创建Book类,并编写set方法和get方法 package com.bean; public class Book { private int id; private String name; ...

  9. c# .Net :Excel NPOI导入导出操作教程之读取Excel文件信息及输出

    c# .Net :Excel NPOI导入导出操作教程之读取Excel文件信息及输出 using NPOI.HSSF.UserModel;using NPOI.SS.UserModel;using S ...

随机推荐

  1. 使用 rpython 在 windows 下生成的程序无法运行

    在 windows 用rpython编译出的文件总是无法运行,报 通过跟踪发现,rpython 每次都会将生成的C代码.Makefile 等放置在 %TEMP%\usession-release-2. ...

  2. 谷歌page speed 安装使用及页面问题详解

    原文地址:http://wenku.baidu.com/view/b0a61f3ebcd126fff7050b40.html 谷歌page speed 安装使用及页面问题详解 谷歌page speed ...

  3. 普林斯顿大学算法课 Algorithm Part I Week 3 重复元素排序 - 三路快排 Duplicate Keys

    很多时候排序是为了对数据进行归类,这种排序重复值特别多 通过年龄统计人口 删除邮件列表里的重复邮件 通过大学对求职者进行排序 若使用普通的快排对重复数据进行排序,会造成N^2复杂度,但是归并排序和三路 ...

  4. mysql中多个字段共同确定唯一性

    create table tbl_table ( id integer not null auto_increment, fname varchar(255), lname varchar(255), ...

  5. 依赖注入及AOP简述(十三)——AOP应用举例(完结) .

    2.     AOP应用举例 在一般的应用程序开发中,有一些典型的AOP应用,使得开发者可以专注于业务逻辑本身,而不是与之完全无关的一些“方面”. l        首先就是关于前面介绍过的日志输出类 ...

  6. SQL整理5

    主键(PRIMARY KEY ) 来自MSDN的描述: 表通常具有包含唯一标识表中每一行的值的一列或一组列.这样的一列或多列称为表的主键 (PK),用于强制表的实体完整性.在创建或修改表时,您可以通过 ...

  7. winform CheckedListBox实现全选/全不选

    /全选         private void button3_Click(object sender, EventArgs e)         {             for (int i ...

  8. vs2015 不支持javascript的智能提示高亮

    有些人安装了vs2015后发现居然不支持javascrpt的高亮功能,连工具-选项-文本编辑器里面的javascript也没有了,楼主也碰到这么个情况了,估计是有与装了多个版本的原因,楼主电脑安装了V ...

  9. Sql Server数据库--》事务

    事务:更多的是一种处理机制(同生共死) 事务是对增删改而言的(因为她们会改变数据) 事务是对多条语句而言,多个sql语句组成,整体执行 事务的4个特点叫做ACID:分别为: 1,A:原子性->事 ...

  10. Java Eclipse常规设置

    改变字体大小 eclipse英文版中如何去修改字体及方法?首先打开eclipse中,按下面的方法即可菜单项:window ->preferences -> general -> ap ...