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. JAVA的IO运用

    IO OF JAVA想写好一篇关于JAVA的IO的文章不容易,因为它涉及的东西很多难以写得有深度和有思路.我虽不才但也写.这篇文章有我个人不少的见解,虽然涉足计算机不深但我不想用一大堆这个可能那个可能 ...

  2. nova availability zone

    find a bug: at first there is only one zone. create aggregate host1 in zone1 create aggregate host1 ...

  3. java 为pdf添加水印图片

    首先需要引入两个Jar包分别是:iTextAsian.jar .itext-2.1.7.jar  可以去  http://download.csdn.net/detail/work201003/922 ...

  4. C#.net连接SQLite及遇到的问题

    1.Slite简介 SQLite,是一款轻型的数据库,是遵守ACID的关联式数据库管理系统,它的设计目标是嵌入式的,而且目前已经在很多嵌入式产品中使用了它,它占用资源非常的低,在嵌入式设备中,可能只需 ...

  5. iOS的Ping++支付接入步骤(详细)

    Ping++ SDK 代码下载地址: https://github.com/CoderLeezhen/PingppDemo 参考链接: https://www.pingxx.com/guidance/ ...

  6. Node.js(转) -- 临时来说还看不懂!

    转自:http://blog.jobbole.com/53736/ 本文由 伯乐在线 - Lellansin 翻译.未经许可,禁止转载!英文出处:toptal.欢迎加入翻译组. 介绍 JavaScri ...

  7. poj1700--贪心算法

    题意:一群人坐船过河,船只有一辆,且一次最多坐两人,时间按慢的算.求最短过河时间? 总共有两种做法可使用: 1.先让最快和次快的过去,让最快的把船开回,再让最慢和次慢的过去,让次快的把船开回.需两个来 ...

  8. MFC网络编程

    一.概念1.同步方式与异步方式同步方式:发送方不等接收方响应,便接着发送下一个数据包的通信方式异步方式:发送方发出数据,等收到接收方发回的响应后,才发送下一个数据包的通信方式2.阻塞与非阻塞方式阻塞套 ...

  9. JS倒计时器一只,顺便复习javascript时间相关函数

    window.onload = function(){ var uS = 604800; //后台提供 : 秒 var day=hour=minute=second=0, timer; var dem ...

  10. 图的邻接链表实现(c)

    参考:算法:C语言实现 一书 实现: #ifndef GRAPH #define GRAPH #include<stdio.h> #include<stdlib.h> stru ...