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. mysql mysqldump只导出表结构或只导出数据的实现方法

    mysql mysqldump只导出表结构或只导出数据的实现方法,需要的朋友可以参考下. mysql mysqldump 只导出表结构 不导出数据 复制代码代码如下: mysqldump --opt ...

  2. UML include、generalization、extend、association

    1.别人的说法 转自:http://www.cnblogs.com/shinings/archive/2009/04/21/1440765.html 共性:都是从现有的用例中抽取出公共的那部分信息,作 ...

  3. linux grep、find 命令详解

    grep1.作用grep命令可以指定文件中搜索特定的内容,并将含有这些内容的行标准输出.grep全称是Global Regular Expression Print,表示全局正则表达式版本,它的使用权 ...

  4. ajax,json和$.each()

    json返回的时候,只需要展示部分字段,如果是 ajax从后台获取结果处理,可以使用.select() 等处理结合匿名类,生成需要的字段的匿名类json字符串,返回前端,可以使用$.parseJson ...

  5. 提升网站性能之设置gzip

    tomcat如何设置gzip: http://www.tuicool.com/articles/aMRRFre http://blog.csdn.net/xuefeng0707/article/det ...

  6. SCRUM,一个采用迭代,增量方法来优化可预见控制风险

    Scrum是一个用于开发和维持复杂产品的框架,是一个增量的,迭代的开发过程.在这个框架中,整个开发过程是由若干个短的迭代周期组成,一个短的迭代周期称为一个Sprint,每个Sprint的建议长度是2到 ...

  7. Mysql异常:MySQLNonTransientConnectionException: No operations allowed after statement closed

    Mysql异常:MySQLNonTransientConnectionException: No operations allowed after statement closed MySQLNonT ...

  8. EL表达式中如何截取字符串

    EL表达式中如何截取字符串 可以截取,用fn函数:<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/ ...

  9. 贪心算法——将正整数变为1

    题目链接http://toutiao.com/a6320936270101528833/ 为避免链接失效,再粘贴一下题目内容: 给你一个数n,有3种操作: 1.这个数加1 2.这个数减1 3.如果这个 ...

  10. 用MT.exe将exe中的manifest文件提取出来和将manifest文件放入exe中

     前一种方法是将manifest文件放入exe中,但是要记得需要在工程中设置 这样的话exe中就不存在manifest了,在debug目录下就会看到相应的manifest文件.后者是将exe中的man ...