NPOI excel文件解析
一、导入excel时要解析文件,我们直接用下面的帮助数来解析就可以了,开始是上使用该类的方法
private void ImportPlanPersonFromExcel(HttpContext context)
{
try
{
context.Response.ContentType = "text/plain";
context.Response.Charset = "utf-8";
string planIdStr = context.Request.QueryString["planId"];
if (string.IsNullOrEmpty(planIdStr))
{
planIdStr = context.Request["planId"];
}
int planId = int.Parse(planIdStr);
HttpPostedFile file = context.Request.Files["Filedata"];
List<ImportPlanPersonExcel> ippe = new List<ImportPlanPersonExcel>();
//接受到的文件流为空或者大小为0
if (file == null || file.ContentLength == )
{
if (context.Session["CheckPassPlanperson"] != null)
{
ippe = (List<ImportPlanPersonExcel>)context.Session["CheckPassPlanperson"];
}
else
{
throw new Exception("文件不能为空!");
} }
else
{
//获取文件名称
var lastnam = Path.GetExtension(file.FileName).ToLower();
ippe = ExcelHelper.ReadExcel<ImportPlanPersonExcel>(new[] { "IndexNo", "Name", "Position", "JobName", "CountryName", "StartDate", "MissionType", "Explain", "Remark" }, file.InputStream, lastnam);
} string currUserUnitCode = ProfileHelper.GetCurrentUsersUnitCode();
string msg = SaveToDB(ippe, planId, currUserUnitCode);
if (string.IsNullOrEmpty(msg))
context.Response.Write("ok");
else
context.Response.Write(msg);
}
catch (Exception ex)
{
context.Response.Write(ex.Message);
}
}
二、解析excel帮助类
//缺少编译器要求的成员“ystem.Runtime.CompilerServices.ExtensionAttribute..ctor”
namespace System.Runtime.CompilerServices
{
public class ExtensionAttribute : Attribute { }
} namespace OilDigital.CGGL.Web
{
public static class ExcelHelper
{
/// <summary>
/// 获取单元格的值
/// </summary>
/// <param name="sheet">Excel sheet表名称</param>
/// <param name="rowIndex">行索引</param>
/// <param name="cellIndex">列索引</param>
/// <returns>行索引和列索引从0开始</returns>
///这个方法是用来检查如果你不知道你的单元格里的值是什么类型的就可以用这个方法检查
///返回的字符串代表了单元格内容的值类型
public static string GetCellValue(this ISheet sheet, int rowIndex, int cellIndex)
{
string returnValue = string.Empty;
//拼接的条件
if (sheet != null)
{
//如果当前的sheet不等于空 则获取索引行的值
var row = sheet.GetRow(rowIndex);
if (row != null)
{
//如果行内容不为空 则获取列
var cell = row.GetCell(cellIndex);
if (cell != null)
{
//列也不为空则判断列中的值的类型
switch (cell.CellType)
{
//如果为string类型,则返回String类型
case CellType.String:
returnValue = cell.StringCellValue;
break;
//如果是数字类类型
case CellType.Numeric:
//判断是否为日期类型
if (DateUtil.IsCellDateFormatted(cell))
{
//是日期类型则转化成日期输出
returnValue = DateTime.FromOADate(cell.NumericCellValue).ToString();
}
else
{
//输出数字类型
returnValue = Convert.ToDouble(cell.NumericCellValue).ToString();
}
break;
//是否是bool类型
case CellType.Boolean:
returnValue = Convert.ToString(cell.BooleanCellValue);
break;
//错误函数类型
case CellType.Error:
returnValue = ErrorEval.GetText(cell.ErrorCellValue);
break;
case CellType.Formula:
switch (cell.CachedFormulaResultType)
{
case CellType.String:
string strFORMULA = cell.StringCellValue;
if (strFORMULA != null && strFORMULA.Length > )
{
returnValue = strFORMULA.ToString();
}
break;
case CellType.Numeric:
returnValue = Convert.ToString(cell.NumericCellValue);
break;
case CellType.Boolean:
returnValue = Convert.ToString(cell.BooleanCellValue);
break;
case CellType.Error:
returnValue = ErrorEval.GetText(cell.ErrorCellValue);
break;
default:
break;
}
break;
default: break;
}
}
}
}
return returnValue.Trim();
}
/// <summary>
/// Excel导入
/// </summary>
/// <typeparam name="T">这个方法是将Excle转化成泛型导入</typeparam>
/// <param name="columns">数组形式 列头</param>
/// <param name="excelStream">文件流</param>
/// <param name="excelType">文件类型</param>
/// <returns>这是Excel导入List泛型导入</returns>
public static List<T> ReadExcel<T>(string[] columns, Stream excelStream, string excelType = ".xlsx")
{
//先建立一个泛型
var result = new List<T>();
int j=, k=;
try
{
//创建一个空的文件薄
IWorkbook workbook = null;
//如果文件类型为xlsx
//做这个判断使检测Excel的版本的
if (excelType == ".xlsx")
{
//空的文件博等于XSSFWorkbook读取文件流
workbook = new XSSFWorkbook(excelStream);
}
else
{
//如果是.xls就是HSSFWorkbook读取文件流
workbook = new HSSFWorkbook(excelStream);
}
//工作簿是否大于零?如果大于零获取第一个工作薄的内容,否则空值
ISheet sheet = workbook.NumberOfSheets > ? workbook.GetSheetAt() : null;
if (sheet == null)
{
//工作薄如果为空值 转化失败
return result;
}
//这里定义的是反射类型
var type = typeof(T);
//遍历工作薄的内容 for (j = ; j <= sheet.LastRowNum-; j++)//第一行默认是表头再去掉后面的说明的1行
{ //动态创建动态类
var model = Activator.CreateInstance(type);
//行的值来自于sheet获取坐标为j的内容 因为第一行默认为表头,所以j从1开始
IRow row = sheet.GetRow(j);
if (row != null)
{
//columns导入的Excel标题头
for ( k = ; k < columns.Length; k++)
{
//pro得到的列头的类型
var pro = type.GetProperty(columns[k]);
if (pro != null)
{
//声明一个弱类型
Object value;
//列值获取
ICell cell = row.GetCell(k);
//处理获取到的列值类型
switch (cell.CellType)
{
case CellType.Blank: //空数据类型处理
value = null;
break;
case CellType.String: //字符串类型
value = cell.StringCellValue;
break;
case CellType.Numeric: //数字类型
if (DateUtil.IsCellDateFormatted(cell))//日期类型
{
value = cell.DateCellValue;
}
else//其他数字类型
{
value = cell.NumericCellValue;
}
break;
case CellType.Formula:
HSSFFormulaEvaluator e = new HSSFFormulaEvaluator(workbook);
value = e.Evaluate(cell).StringValue;
break;
default:
value = null;
break;
}
if (value != null)
{ if (pro.GetType().Name == typeof(string).Name)
{
//插入值
pro.SetValue(model, Convert.ChangeType(value.ToString(), pro.PropertyType), null);
}
else
pro.SetValue(model, Convert.ChangeType(value, pro.PropertyType), null);
}
}
}
//将得到的值插入到T中(将T强制转化为Model类)
result.Add((T)model);
}
}
}
catch (Exception ex)
{
throw new Exception("excel读取失败:第"+j+"行第"+k+"列数据错误:", ex);
}
return result;
} /// <summary>
/// 将sheet中的数据导出到datatable中
/// </summary>
/// <param name="sheet">需要导出的sheet</param>
/// <param name="HeaderRowIndex">表头所在行号,-1表示没有表头</param>
/// <returns>将Excel导出成Datatable</returns>
private static DataTable ImportDt(ISheet sheet, int HeaderRowIndex, bool needHeader)
{
//新创建一个datatable
DataTable table = new DataTable();
IRow headerRow;
int cellCount;
try
{
//表头索引小于零时 输出表头
if (HeaderRowIndex < || !needHeader)
{
//获取行索引为sheet表第一行
headerRow = sheet.GetRow();
//获取不为空的列个数
cellCount = headerRow.LastCellNum;
//获取第一列的值
for (int i = headerRow.FirstCellNum; i <= cellCount; i++)
{
DataColumn column = new DataColumn(Convert.ToString(i));
table.Columns.Add(column);
}
}
else
{
//获取行内容
headerRow = sheet.GetRow(HeaderRowIndex);
cellCount = headerRow.LastCellNum;
//获取第一行第一个单元格内容
for (int i = headerRow.FirstCellNum; i <= cellCount; i++)
{
if (headerRow.GetCell(i) == null)
{
if (table.Columns.IndexOf(Convert.ToString(i)) > )
{
DataColumn column = new DataColumn(Convert.ToString("重复列名" + i));
table.Columns.Add(column);
}
else
{
DataColumn column = new DataColumn(Convert.ToString(i));
table.Columns.Add(column);
} }
else if (table.Columns.IndexOf(headerRow.GetCell(i).ToString()) > )
{
DataColumn column = new DataColumn(Convert.ToString("重复列名" + i));
table.Columns.Add(column);
}
else
{
DataColumn column = new DataColumn(headerRow.GetCell(i).ToString());
table.Columns.Add(column);
}
}
}
int rowCount = sheet.LastRowNum;
for (int i = (HeaderRowIndex + ); i <= sheet.LastRowNum; i++)
{
try
{
IRow row;
if (sheet.GetRow(i) == null)
{
row = sheet.CreateRow(i);
}
else
{
row = sheet.GetRow(i);
} DataRow dataRow = table.NewRow(); for (int j = row.FirstCellNum; j <= cellCount; j++)
{
try
{
if (row.GetCell(j) != null)
{
switch (row.GetCell(j).CellType)
{
case CellType.String:
string str = row.GetCell(j).StringCellValue;
if (str != null && str.Length > )
{
dataRow[j] = str.ToString();
}
else
{
dataRow[j] = null;
}
break;
case CellType.Numeric:
if (DateUtil.IsCellDateFormatted(row.GetCell(j)))
{
dataRow[j] = DateTime.FromOADate(row.GetCell(j).NumericCellValue);
}
else
{
dataRow[j] = Convert.ToDouble(row.GetCell(j).NumericCellValue);
}
break;
case CellType.Boolean:
dataRow[j] = Convert.ToString(row.GetCell(j).BooleanCellValue);
break;
case CellType.Error:
dataRow[j] = ErrorEval.GetText(row.GetCell(j).ErrorCellValue);
break;
case CellType.Formula:
switch (row.GetCell(j).CachedFormulaResultType)
{
case CellType.String:
string strFORMULA = row.GetCell(j).StringCellValue;
if (strFORMULA != null && strFORMULA.Length > )
{
dataRow[j] = strFORMULA.ToString();
}
else
{
dataRow[j] = null;
}
break;
case CellType.Numeric:
dataRow[j] = Convert.ToString(row.GetCell(j).NumericCellValue);
break;
case CellType.Boolean:
dataRow[j] = Convert.ToString(row.GetCell(j).BooleanCellValue);
break;
case CellType.Error:
dataRow[j] = ErrorEval.GetText(row.GetCell(j).ErrorCellValue);
break;
default:
dataRow[j] = "";
break;
}
break;
default:
dataRow[j] = "";
break;
}
}
}
catch (Exception exception)
{
throw new Exception(exception.Message);
}
}
table.Rows.Add(dataRow);
}
catch (Exception exception)
{
throw new Exception(exception.Message);
}
}
}
catch (Exception exception)
{
throw new Exception(exception.Message);
}
return table;
}
}
}
NPOI excel文件解析的更多相关文章
- NPOI+Json文件解析Excel
记点笔记,加深印象!最近有个导入Excel工能需要完成,Excel列名是中文的,导入Excel我用的NPOI插件,如果不对Excel做解析,列名有可能会给我带来一些字符方面的麻烦,于是想到了一个比较l ...
- java使用POI进行 Excel文件解析
package com.timevale.esign.vip.util; import java.io.File; import java.io.FileInputStream; import jav ...
- 关于Npoi+excel文件读取,修改文件内容的处理方式
因最近有需求场景,实现对文件的读写操作,又不单独生成新的文件,对于源文件的修改,做了一个简单实现,如下↓ // 要操作的excel文件路径 string fileName = Server.MapPa ...
- vue下载和上传excle数据文件,解析excel文件数据并存在数据库中
下载: VUE: window.open("xxxx/downloadOldTaskDataFile.do_", "_blank"); JAVA: /** * ...
- 使用(POI)SAX处理Excel文件,防止内存溢出
POISAXReader h2:first-child, body>h1:first-child, body>h1:first-child+h2, body>h3:first-chi ...
- 【转】java将excel文件转换成txt格式文件
在实际应用中,我们难免会遇到解析excel文件入库事情,有时候为了方便,需要将excel文件转成txt格式文件.下面代码里面提供对xls.xlsx两种格式的excel文件解析,并写入到一个新的txt文 ...
- Java使用jxl.jar包写Excel文件的最适合列宽问题基本实现
以前用jxl.jar包,读写过Excel文件.也没有注意最适合列宽的问题,但是jxl.jar没有提供最适合列宽的功能,上次用到写了一下,可以基本实现最适合列宽. 注意,这个只是基本可以实现,基本针对中 ...
- NPOI操作EXCEL(四)——反射机制批量导出excel文件
前面我们已经实现了反射机制进行excel表格数据的解析,既然有上传就得有下载,我们再来写一个通用的导出方法,利用反射机制实现对系统所有数据列表的筛选结果导出excel功能. 我们来构想一下这样一个画面 ...
- C#仪器数据文件解析-Excel文件(xls、xlsx)
不少仪器工作站可以将数据导出为Excel文件,包括97-2003版本的xls文件和2007+的xlsx文件. 采集Excel文件相比采集pdf文件更容易.程序更健壮,毕竟Excel中数据有明确的行.列 ...
随机推荐
- NLP常用开源/免费工具
一些常见的NLP任务的开源/免费工具, *Computational Linguistics ToolboxCLT http://complingone.georgetown.edu/~linguis ...
- C#多线程学习(四) 多线程的自动管理(线程池)
在多线程的程序中,经常会出现两种情况: 一种情况: 应用程序中,线程把大部分的时间花费在等待状态,等待某个事件发生,然后才能给予响应 这一般使用ThreadPo ...
- 常用的jQuery学习文档及使用经验
分享几个jQuery学习的API在线文档 1. 首推 http://hemin.cn/jq/ 原因是全中文文档,文档排列通俗易懂,容易查找,示例清楚. 2. https://www.jquery123 ...
- 如果使用安卓4.4的SD卡?
安卓4.4默认情况下,后安装的程序无权写入数据到SD卡中,那么是否我们就不能用了?看了很多文章,都说要Root,随后修改配置文件.我觉得这不是很好的方法,Root之后的安卓会有很大风险,这不是最好的办 ...
- 苹果软件App上架问题
0.官方网站 开发者中心 itunes connect 优酷 哔哩哔哩 腾讯视频 1.上架流程 1.1 开发者账号申请 2017年苹果企业开发者账请完号申整指南 iOS开发之苹果开发者账号注册申请流程 ...
- django admin的自定制
from django.contrib import admin # Register your models here. from .models import * from django.util ...
- [CTSC2010]星际旅行
https://www.luogu.org/problemnew/show/P4189 题解 模拟费用流. 首先有一个非常好的条件,每个点的限制次数都大于等于这个点的度数. 然后我们可以从\(0\)开 ...
- [转] iOS中@class #import #include 简介
[转载自:http://blog.csdn.net/chengwuli125/article/details/9705315] 一.解析 很多刚开始学习iOS开发的同学可能在看别人的代码 ...
- [集合]Collection集合框架源码分析
Collection接口 在java的集合类库中,基本接口是Collection,该接口的在集合中的源码定义如下(将源码中的注释删掉了): public interface Collection< ...
- webpack构建多页面react项目(webpack+typescript+react)
目录介绍 src:里面的每个文件夹就是一个页面,页面开发相关的组件.图片和样式文件就存放在对应的文件夹下. tpl:里面放置模板文件,当webpack打包时为html-webpack-plugin插件 ...