using System.Data;
using System.IO;
using System.Text;
using System.Web;
using NPOI.SS.UserModel;
using NPOI.HSSF.UserModel; namespace AIMSCommon
{
public class ExcelRender
{
/// <summary>
/// 根据Excel列类型获取列的值
/// </summary>
/// <param name="cell">Excel列</param>
/// <returns></returns>
private static string GetCellValue(ICell cell)
{
if (cell == null)
return string.Empty;
switch (cell.CellType)
{
case CellType.BLANK:
return string.Empty;
case CellType.BOOLEAN:
return cell.BooleanCellValue.ToString();
case CellType.ERROR:
return cell.ErrorCellValue.ToString();
case CellType.NUMERIC:
case CellType.Unknown:
default:
return cell.ToString();
case CellType.STRING:
return cell.StringCellValue;
case CellType.FORMULA:
try
{
HSSFFormulaEvaluator e = new HSSFFormulaEvaluator(cell.Sheet.Workbook);
e.EvaluateInCell(cell);
return cell.ToString();
}
catch
{
return cell.NumericCellValue.ToString();
}
}
} /// <summary>
/// 自动设置Excel列宽
/// </summary>
/// <param name="sheet">Excel表</param>
private static void AutoSizeColumns(ISheet sheet)
{
if (sheet.PhysicalNumberOfRows > 0)
{
IRow headerRow = sheet.GetRow(0); for (int i = 0, l = headerRow.LastCellNum; i < l; i++)
{
sheet.AutoSizeColumn(i);
}
}
} /// <summary>
/// 保存Excel文档流到文件
/// </summary>
/// <param name="ms">Excel文档流</param>
/// <param name="fileName">文件名</param>
private static void SaveToFile(MemoryStream ms, string fileName)
{
using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write))
{
byte[] data = ms.ToArray(); fs.Write(data, 0, data.Length);
fs.Flush(); data = null;
}
} /// <summary>
/// 输出文件到浏览器
/// </summary>
/// <param name="ms">Excel文档流</param>
/// <param name="context">HTTP上下文</param>
/// <param name="fileName">文件名</param>
private static void RenderToBrowser(MemoryStream ms, HttpContext context, string fileName)
{
if (context.Request.Browser.Browser == "IE")
fileName = HttpUtility.UrlEncode(fileName);
context.Response.AddHeader("Content-Disposition", "attachment;fileName=" + fileName);
context.Response.BinaryWrite(ms.ToArray());
} /// <summary>
/// DataTable转换成Excel文档流
/// </summary>
/// <param name="table"></param>
/// <returns></returns>
public static MemoryStream RenderToExcel(DataTable table)
{
MemoryStream ms = new MemoryStream();
using (table)
{
using (IWorkbook workbook = new HSSFWorkbook())
{
using (ISheet sheet = workbook.CreateSheet())
{
IRow headerRow = sheet.CreateRow(0);
foreach (DataColumn column in table.Columns)
headerRow.CreateCell(column.Ordinal).SetCellValue(column.Caption);
int rowIndex = 1;
foreach (DataRow row in table.Rows)
{
IRow dataRow = sheet.CreateRow(rowIndex);
foreach (DataColumn column in table.Columns)
{
dataRow.CreateCell(column.Ordinal).SetCellValue(row[column].ToString());
}
rowIndex++;
}
AutoSizeColumns(sheet);
workbook.Write(ms);
ms.Flush();
ms.Position = 0;
}
}
}
return ms;
} /// <summary>
/// DataTable转换成Excel文档流,并保存到文件
/// </summary>
/// <param name="table"></param>
/// <param name="fileName">保存的路径</param>
public static void RenderToExcel(DataTable table, string fileName)
{
using (MemoryStream ms = RenderToExcel(table))
{
SaveToFile(ms, fileName);
}
} /// <summary>
/// DataTable转换成Excel文档流,并输出到客户端
/// </summary>
/// <param name="table"></param>
/// <param name="response"></param>
/// <param name="fileName">输出的文件名</param>
public static void RenderToExcel(DataTable table, HttpContext context, string fileName)
{
using (MemoryStream ms = RenderToExcel(table))
{
RenderToBrowser(ms, context, fileName);
}
} /// <summary>
/// Excel文档流是否有数据
/// </summary>
/// <param name="excelFileStream">Excel文档流</param>
/// <returns></returns>
public static bool HasData(Stream excelFileStream)
{
return HasData(excelFileStream, 0);
} /// <summary>
/// Excel文档流是否有数据
/// </summary>
/// <param name="excelFileStream">Excel文档流</param>
/// <param name="sheetIndex">表索引号,如第一个表为0</param>
/// <returns></returns>
public static bool HasData(Stream excelFileStream, int sheetIndex)
{
using (excelFileStream)
{
using (IWorkbook workbook = new HSSFWorkbook(excelFileStream))
{
if (workbook.NumberOfSheets > 0)
{
if (sheetIndex < workbook.NumberOfSheets)
{
using (ISheet sheet = workbook.GetSheetAt(sheetIndex))
{
return sheet.PhysicalNumberOfRows > 0;
}
}
}
}
}
return false;
} /// <summary>
/// Excel文档流转换成DataTable
/// 第一行必须为标题行
/// </summary>
/// <param name="excelFileStream">Excel文档流</param>
/// <param name="sheetName">表名称</param>
/// <returns></returns>
public static DataTable RenderFromExcel(Stream excelFileStream, string sheetName)
{
return RenderFromExcel(excelFileStream, sheetName, 0);
} /// <summary>
/// Excel文档流转换成DataTable
/// </summary>
/// <param name="excelFileStream">Excel文档流</param>
/// <param name="sheetName">表名称</param>
/// <param name="headerRowIndex">标题行索引号,如第一行为0</param>
/// <returns></returns>
public static DataTable RenderFromExcel(Stream excelFileStream, string sheetName, int headerRowIndex)
{
DataTable table = null; using (excelFileStream)
{
using (IWorkbook workbook = new HSSFWorkbook(excelFileStream))
{
using (ISheet sheet = workbook.GetSheet(sheetName))
{
table = RenderFromExcel(sheet, headerRowIndex);
}
}
}
return table;
} /// <summary>
/// Excel文档流转换成DataTable
/// 默认转换Excel的第一个表
/// 第一行必须为标题行
/// </summary>
/// <param name="excelFileStream">Excel文档流</param>
/// <returns></returns>
public static DataTable RenderFromExcel(Stream excelFileStream)
{
return RenderFromExcel(excelFileStream, 0, 0);
} /// <summary>
/// Excel文档流转换成DataTable
/// 第一行必须为标题行
/// </summary>
/// <param name="excelFileStream">Excel文档流</param>
/// <param name="sheetIndex">表索引号,如第一个表为0</param>
/// <returns></returns>
public static DataTable RenderFromExcel(Stream excelFileStream, int sheetIndex)
{
return RenderFromExcel(excelFileStream, sheetIndex, 0);
} /// <summary>
/// Excel文档流转换成DataTable
/// </summary>
/// <param name="excelFileStream">Excel文档流</param>
/// <param name="sheetIndex">表索引号,如第一个表为0</param>
/// <param name="headerRowIndex">标题行索引号,如第一行为0</param>
/// <returns></returns>
public static DataTable RenderFromExcel(Stream excelFileStream, int sheetIndex, int headerRowIndex)
{
DataTable table = null; using (excelFileStream)
{
using (IWorkbook workbook = new HSSFWorkbook(excelFileStream))
{
using (ISheet sheet = workbook.GetSheetAt(sheetIndex))
{
table = RenderFromExcel(sheet, headerRowIndex);
}
}
}
return table;
} /// <summary>
/// Excel表格转换成DataTable
/// </summary>
/// <param name="sheet">表格</param>
/// <param name="headerRowIndex">标题行索引号,如第一行为0</param>
/// <returns></returns>
private static DataTable RenderFromExcel(ISheet sheet, int headerRowIndex)
{
DataTable table = new DataTable(); IRow headerRow = sheet.GetRow(headerRowIndex);
int cellCount = headerRow.LastCellNum;//LastCellNum = PhysicalNumberOfCells
int rowCount = sheet.LastRowNum;//LastRowNum = PhysicalNumberOfRows - 1 //handling header.
for (int i = headerRow.FirstCellNum; i < cellCount; i++)
{
DataColumn column = new DataColumn(headerRow.GetCell(i).StringCellValue);
table.Columns.Add(column);
} for (int i = (sheet.FirstRowNum + 1); i <= rowCount; i++)
{
IRow row = sheet.GetRow(i);
DataRow dataRow = table.NewRow(); if (row != null)
{
for (int j = row.FirstCellNum; j < cellCount; j++)
{
if (row.GetCell(j) != null)
dataRow[j] = GetCellValue(row.GetCell(j));
}
} table.Rows.Add(dataRow);
} return table;
}
}
}

根据Excel列类型获取列的值的更多相关文章

  1. 潭州课堂25班:Ph201805201 第六课:散列类型,运算符优先级和逻辑运算 (课堂笔记)

    # # 集合:# se1 = { 1,3,4,5,'a'} # 如果直接添加元素,不能直接添加可变元素# se2 = set() # 定义一个空集合# se3 = {'a'} # 定义个单元素的集合# ...

  2. 7、python基本数据类型之散列类型

    前言:python的基本数据类型可以分为三类:数值类型.序列类型.散列类型,本文主要介绍散列类型. 一.散列类型 内部元素无序,不能通过下标取值 1)字典(dict):用 {} 花括号表示,每一个元素 ...

  3. 数据库-SQL语句:删除和修改语句-列类型-列约束

    使用MySQL客户端连接服务器的两种方式: (1)交互模式: ——查 mysql.exe  -h127.0.0.1  -uroot  -p mysql   -uroot (2)脚本模式:——增删改 m ...

  4. Django一对一查询,列类型及参数

    一对一查询 表的创建 # 通过 OneToOneField 创建一对一的关系 from django.db import models # Create your models here. class ...

  5. GridView控件RowDataBound事件中获取列字段值的几种途径 !!!

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == ...

  6. GridView控件RowDataBound事件中获取列字段值的几种途径

    前台: <asp:TemplateField HeaderText="充值总额|账号余额"> <ItemTemplate> <asp:Label ID ...

  7. excel 两列 找出相同的值

    excel 有A,B两列数值,要找出A,B两列中数值相同的值. 选中B列,格式——条件格式——公式  输入:=countif(A:A,B1)  在格式中可选择突出字体颜色 该函数的语法规则如下: co ...

  8. asp.net动态添加GridView的模板列,并获取列值

    一.动态添加模板列: 1.建立模板列样式: 说明:下边代码可以直接写在aspx文件中,也可以单独建立cs文件:另外,我没有写button.linkButton等控件,意思差不多,不过当需要添加事件时, ...

  9. C# 根据列名获取列值

    /// <summary> /// 根据列名获取列值 /// </summary> /// <param name="colName">< ...

随机推荐

  1. MVC5+EF6+BootStrap3.3.5 博客系统之EF(一)

  2. 【BZOJ2199】 [Usaco2011 Jan]奶牛议会

    Description 由于对Farmer John的领导感到极其不悦,奶牛们退出了农场,组建了奶牛议会.议会以“每头牛 都可以获得自己想要的”为原则,建立了下面的投票系统: M只到场的奶牛 (1 & ...

  3. swift基础--数组、字典

    (1)初始化 (2)新增.修改.删除 (3)清空 (4)遍历 var array1 = ["x","y","z"] var array2:[ ...

  4. 关于HTML Input

    定义:<input> 标签用于搜集用户信息.Input表示Form表单中的一种输入对象. 根据不同的 type 属性值,输入字段拥有很多种形式.输入字段可以是文本字段.复选框(单/复选框) ...

  5. 3.4 spring- lookup-method 子元素的使用与解析

    1. lookup-method的应用: 1.1 子元素lookup-method 似乎不是很常用,但是在某些时候他的确是非常有用的属性,通常我们称它为 "获取器注入" . 引用 ...

  6. C#学习笔记(二)

    1.注释:注销,解释2.单行://多行:/**/文档注释:///按enter主食要保证 别人一看就明白3.快速对期待吗:ctrl+k+d,按住ctrl不放,按k,迅速抬起,再按d(按D得时候k已经抬起 ...

  7. Akka Stream文档翻译:Quick Start Guide: Reactive Tweets

    Quick Start Guide: Reactive Tweets 快速入门指南: Reactive Tweets (reactive tweets 大概可以理解为“响应式推文”,在此可以测试下GF ...

  8. 【leetcode】Word Break II (hard)★

    Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where each ...

  9. 利用Spring AOP自定义注解解决日志和签名校验

    转载:http://www.cnblogs.com/shipengzhi/articles/2716004.html 一.需解决的问题 部分API有签名参数(signature),Passport首先 ...

  10. SQLite数据类型详解

    一.存储种类和数据类型: SQLite将数据值的存储划分为以下几种存储类型: 复制代码代码如下:      NULL: 表示该值为NULL值.      INTEGER: 无符号整型值.      R ...