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. C/C++源代码的Include依赖关系图

    前一篇博文中我曾仔细介绍过如何查看C/C++代码的依赖项关系图,在这篇文章中我将会介绍如何使用Visualization and Modeling Feature Pack 工具包,查看C/C++源代 ...

  2. 网易云课堂_程序设计入门-C语言_第四周:循环控制_2念整数

    2 念整数(5分) 题目内容: 你的程序要读入一个整数,范围是[-100000,100000].然后,用汉语拼音将这个整数的每一位输出出来. 如输入1234,则输出: yi er san si 注意, ...

  3. float

    .clearfix:after { visibility: hidden; display: block; font-size: 0; content: " "; clear: b ...

  4. [UI]抽屉菜单DrawerLayout分析(三)

    在[UI]抽屉菜单DrawerLayout分析(一)和[UI]抽屉菜单DrawerLayout分析(二)中分别介绍了DrawerLayout得基本框架结构和ViewDragerHelper的作用以及手 ...

  5. linux下创建用户并且限定用户主目录

    Linux 系统是一个多用户多任务的分时操作系统,任何一个要使用系统资源的用户,都必须首先向系统管理员申请一个账号,然后以这个账号的身份进入系统.用户的账号 一方面可以帮助系统管理员对使用系统的用户进 ...

  6. window.onload()与$(document).ready()区别

    浏览器加载完DOM后,会通过javascript为DOM元素添加事件,在javascript中,通常使用window.onload()方法. 在jquery中,则使用$(document).ready ...

  7. Android 如何让 app 自行处理 power key M

    前言          欢迎大家我分享和推荐好用的代码段~~ 声明          欢迎转载,但请保留文章原始出处:          CSDN:http://www.csdn.net        ...

  8. DB2 相关操作

      查看数据库版本:db2level DB21061E  Command line environment not initialized. windows命令行下,需要先调用db2cmd,或者DB2 ...

  9. 几种改变Activity回退栈默认行为的Intent Flag

    FLAG_与LaunchMode相比最大的不同是临时性 1.FLAG_ACTIVITY_NEW_TASK: Developer.android.com的说法: (1)在新的task中启动这个Activ ...

  10. 如何彻底卸载sql server 2012

    好不容易装上了sql server 2012数据库,可是却不能连接本地的数据库,后来发现缺少一些服务,于是决定重新安装,但是卸载却很麻烦,如果卸载不干净的话,重新安装会出问题,所以下面就总结一些方法: ...