/// <summary>
/// EXCEL转DataTable
/// </summary>
/// <param name="postedfile">上传的文件对象</param>
/// <returns>返回一张table</returns>
static FileStream stream;
static DataTable table;
public static object obj = new object();
public static DataTable ImportExcelToDataTable(HttpPostedFile postedfile)
{
lock (obj)
{
if (postedfile != null)
{
try
{
string filename = DateTime.Now.ToString("yyyyMMddhhssmmffffff") + Path.GetExtension(postedfile.FileName);
string fullpath = HttpContext.Current.Server.MapPath("~/AdminSystem/TempFiles/");
if (!Directory.Exists(fullpath))
{
Directory.CreateDirectory(fullpath);
}
fullpath += filename;
postedfile.SaveAs(fullpath);
table = new DataTable();
stream = File.Open(fullpath, FileMode.Open, FileAccess.Read);
XSSFWorkbook workbook = new XSSFWorkbook(stream);
ISheet sheet = workbook.GetSheetAt(0);
//获取sheet的首行
IRow headerRow = sheet.GetRow(0);
int cellCount = headerRow.LastCellNum;
for (int i = headerRow.FirstCellNum; i < cellCount; i++)
{
DataColumn column = new DataColumn(headerRow.GetCell(i).StringCellValue);
table.Columns.Add(column);
}
int rowCount = sheet.LastRowNum;
for (int i = (sheet.FirstRowNum + 1); i <= sheet.LastRowNum; i++)
{
IRow row = sheet.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);
}
stream.Close();
File.Delete(fullpath);
return table;
}
catch
{
table.Dispose();
return null;
}
finally
{
stream.Close();
table.Dispose();
}
}
else
{
return null;
}
}
}
NPOI的EXCEL转DATATABLE
原创Johnny_Cheung 博主文章分类:asp.net ©著作权
©著作权归作者所有:来自51CTO博客作者Johnny_Cheung的原创作品,请联系作者获取转载授权,否则将追究法律责任
下一篇:C#客户端日志记录
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章
-
.net 使用NPOI或MyXls把DataTable导出到Excel
Excel导入及导出问题产生: 从接触.net到现在一直在维护一个DataTable导出到Ex
测试 taro .net asp.net -
NPOI操作Excel(一)--NPOI基础
用C#读取Excel的方法有很多中,由于近期工作需要,需要解析的Excel含有合并单元格以及背景色等特殊要
数据 合并单元格 html c# 背景色 -
NPOI 读取excel到DataTable 读取隐藏列 读取公式列
处理思路:1.打开excel 用NPOI进行读取;2.读取第一个
taro ide i++ 读取数据 打开文件 -
openfeign grpc性能对比
一、基本概念梳理 微服务架构上,都是采用Restful风格进行通信的。1、IPC 进程间通信,Inter-Process Communication指至少两个进程或线程间传送数据或信号的一些技术或方法。每个进程都有自己的一部分独立的系统
openfeign grpc性能对比 spring spring-cloud java ci