MVC execl 导入导出
MVC execl 导入导出
<input id="xls" name="xls" type="file" style="width:210px;" />
<input type="submit" value="导入" />
<a href="~/Demo/Excel_ExcelExport">导出</a> #region Excel public ActionResult Excel_Index()
{
return View();
} [HttpPost]
public ActionResult Excel_Index(FormCollection formdata)
{
ViewBag.Data = null;
ViewBag.Msg = string.Empty; if (this.HttpContext.Request.Files.Count <= || this.HttpContext.Request.Files[].ContentLength <= )
{
ViewBag.Msg = "请选择文件!";
return View();
} string fileExt = System.IO.Path.GetExtension(this.HttpContext.Request.Files[].FileName).ToLower();
if (fileExt != ".xls" && fileExt != ".xlsx")
{
ViewBag.Msg = "选择的文件格式不对!";
return View();
} ViewBag.Data = Demo.ImportFromStream(this.HttpContext.Request.Files[].InputStream); return View();
} public ActionResult Excel_ExcelExport()
{
DataTable dt = new DataTable();
DataColumn dc1 = new DataColumn("column1", Type.GetType("System.String"));
DataColumn dc2 = new DataColumn("column2", Type.GetType("System.String"));
DataColumn dc3 = new DataColumn("column3", Type.GetType("System.String"));
DataColumn dc4 = new DataColumn("column4", Type.GetType("System.String"));
DataColumn dc5 = new DataColumn("column5", Type.GetType("System.String"));
dt.Columns.Add(dc1);
dt.Columns.Add(dc2);
dt.Columns.Add(dc3);
dt.Columns.Add(dc4);
dt.Columns.Add(dc5); for (int i = ; i < ; i++)
{
DataRow dr = dt.NewRow();
dr["column1"] = "test1";
dr["column2"] = "test2";
dr["column3"] = "test3";
dr["column4"] = "test4";
dr["column5"] = "test5";
dt.Rows.Add(dr);
} byte[] bytes = Demo.ExportToBytes(dt); return File(bytes, "application/x-excel", "ExcelExport.xls");
} #endregion
NPOI插件
using NPOI.SS.UserModel; /// <summary>
/// Excel导入导出工具类
/// </summary>
public static class Demo {
/// <summary>
/// 导入Excel
/// </summary>
public static System.Data.DataTable ImportFromStream(System.IO.Stream fileStream)
{
NPOI.SS.UserModel.IWorkbook workbook;
NPOI.SS.UserModel.ISheet sheet;
System.Data.DataTable data = new System.Data.DataTable(); try
{
try
{
workbook = new NPOI.XSSF.UserModel.XSSFWorkbook(fileStream); //
}
catch
{
workbook = new NPOI.HSSF.UserModel.HSSFWorkbook(fileStream); //
} //第一个sheet工作表
sheet = workbook.GetSheetAt(); if (sheet != null)
{
//第一行
IRow firstRow = sheet.GetRow();
int cellCount = firstRow.LastCellNum; //一行最后一个cell的编号 即总的列数 for (int i = firstRow.FirstCellNum; i < cellCount; ++i)
{
System.Data.DataColumn column = new System.Data.DataColumn(firstRow.GetCell(i).StringCellValue);
data.Columns.Add(column);
} //最后一列的标号
int rowCount = sheet.LastRowNum;
for (int i = sheet.FirstRowNum; i <= rowCount; ++i)
{
IRow row = sheet.GetRow(i);
if (row == null) continue; //没有数据的行默认是null System.Data.DataRow dataRow = data.NewRow();
for (int j = row.FirstCellNum; j < cellCount; ++j)
{
//if (row.GetCell(j) != null) //同理,没有数据的单元格都默认是null
// dataRow[j] = row.GetCell(j).ToString();
if (row.GetCell(j) != null) //同理,没有数据的单元格都默认是null
{
switch (row.GetCell(j).CellType)
{
case CellType.String: //文本
dataRow[j] = row.GetCell(j).StringCellValue;
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: //bool
dataRow[j] = row.GetCell(j).BooleanCellValue;
break;
case CellType.Blank: //空白
dataRow[j] = "";
break;
default: dataRow[j] = "ERROR";
break;
}
}
}
data.Rows.Add(dataRow);
}
} return data;
}
catch (Exception)
{
return null;
}
} /// <summary>
/// 导入Excel
/// </summary>
public static System.Data.DataTable ImportFromBytes(byte[] fileBytes)
{
System.Data.DataTable table = null; if (fileBytes == null || fileBytes.Length <= )
{
return table;
} using (var fileStream = new System.IO.MemoryStream(fileBytes))
{
table = ImportFromStream(fileStream);
} return table;
} /// <summary>
/// 导入Excel
/// </summary>
public static System.Data.DataTable ImportFromFilename(string fileName)
{
System.Data.DataTable table = null; if (!System.IO.File.Exists(fileName))
{
return table;
} using (var fileStream = new System.IO.FileStream(fileName, System.IO.FileMode.Open, System.IO.FileAccess.Read))
{
table = ImportFromStream(fileStream);
} return table;
} /// <summary>
/// 导出Excel
/// </summary>
public static System.IO.Stream ExportToStream(System.Data.DataTable table)
{
System.IO.MemoryStream ms = new System.IO.MemoryStream(); NPOI.HSSF.UserModel.HSSFWorkbook workbook = new NPOI.HSSF.UserModel.HSSFWorkbook();
NPOI.SS.UserModel.ISheet sheet = workbook.CreateSheet();
NPOI.SS.UserModel.IRow headerRow = sheet.CreateRow(); IRow headRow = sheet.CreateRow();
foreach (System.Data.DataColumn column in table.Columns)
{
headRow.CreateCell(column.Ordinal).SetCellValue(string.IsNullOrWhiteSpace(column.Caption) ? column.ColumnName : column.Caption);
} int rowIndex = ; foreach (System.Data.DataRow row in table.Rows)
{
IRow dataRow = sheet.CreateRow(rowIndex); foreach (System.Data.DataColumn column in table.Columns)
{
dataRow.CreateCell(column.Ordinal).SetCellValue(row[column].ToString());
} rowIndex++;
}
workbook.Write(ms);
ms.Seek(, System.IO.SeekOrigin.Begin); sheet = null;
headerRow = null;
workbook = null; return ms;
} /// <summary>
/// 导出Excel
/// </summary>
public static byte[] ExportToBytes(System.Data.DataTable table)
{
byte[] bytes = null; using (var stream = ExportToStream(table))
{
bytes = new byte[stream.Length];
stream.Read(bytes, , bytes.Length);
stream.Seek(, System.IO.SeekOrigin.Begin);
} return bytes;
}
}
Datatable导出Excel
//Datatable导出Excel
private static void GridToExcelByNPOI(DataTable dt, string strExcelFileName)
{
try
{
HSSFWorkbook workbook = new HSSFWorkbook();
ISheet sheet = workbook.CreateSheet("Sheet1"); ICellStyle HeadercellStyle = workbook.CreateCellStyle();
HeadercellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
HeadercellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
HeadercellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
HeadercellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
HeadercellStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;
//字体
NPOI.SS.UserModel.IFont headerfont = workbook.CreateFont();
headerfont.Boldweight = (short)FontBoldWeight.Bold;
HeadercellStyle.SetFont(headerfont); //用column name 作为列名
int icolIndex = ;
IRow headerRow = sheet.CreateRow();
foreach (DataColumn item in dt.Columns)
{
ICell cell = headerRow.CreateCell(icolIndex);
cell.SetCellValue(item.ColumnName);
cell.CellStyle = HeadercellStyle;
icolIndex++;
} ICellStyle cellStyle = workbook.CreateCellStyle(); //为避免日期格式被Excel自动替换,所以设定 format 为 『@』 表示一率当成text來看
cellStyle.DataFormat = HSSFDataFormat.GetBuiltinFormat("@");
cellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
cellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
cellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
cellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin; NPOI.SS.UserModel.IFont cellfont = workbook.CreateFont();
cellfont.Boldweight = (short)FontBoldWeight.Normal;
cellStyle.SetFont(cellfont); //建立内容行
int iRowIndex = ;
int iCellIndex = ;
foreach (DataRow Rowitem in dt.Rows)
{
IRow DataRow = sheet.CreateRow(iRowIndex);
foreach (DataColumn Colitem in dt.Columns)
{ ICell cell = DataRow.CreateCell(iCellIndex);
cell.SetCellValue(Rowitem[Colitem].ToString());
cell.CellStyle = cellStyle;
iCellIndex++;
}
iCellIndex = ;
iRowIndex++;
} //自适应列宽度
for (int i = ; i < icolIndex; i++)
{
sheet.AutoSizeColumn(i);
} //写Excel
FileStream file = new FileStream(strExcelFileName, FileMode.OpenOrCreate);
workbook.Write(file);
file.Flush();
file.Close(); MessageBox.Show(m_Common_ResourceManager.GetString("Export_to_excel_successfully"), m_Common_ResourceManager.GetString("Information"), MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch (Exception ex)
{
ILog log = LogManager.GetLogger("Exception Log");
log.Error(ex.Message + Environment.NewLine + ex.StackTrace);
//记录AuditTrail
CCFS.Framework.BLL.AuditTrailBLL.LogAuditTrail(ex); MessageBox.Show(m_Common_ResourceManager.GetString("Export_to_excel_failed"), m_Common_ResourceManager.GetString("Information"), MessageBoxButtons.OK, MessageBoxIcon.Information);
}
finally { workbook = null; } }
Datatable导出Excel
Excel文件导成Datatable
/// <summary>
/// Excel文件导成Datatable
/// </summary>
/// <param name="strFilePath">Excel文件目录地址</param>
/// <param name="strTableName">Datatable表名</param>
/// <param name="iSheetIndex">Excel sheet index</param>
/// <returns></returns>
public static DataTable XlSToDataTable(string strFilePath, string strTableName,int iSheetIndex)
{ string strExtName = Path.GetExtension(strFilePath); DataTable dt = new DataTable();
if (!string.IsNullOrEmpty(strTableName))
{
dt.TableName = strTableName;
} if (strExtName.Equals(".xls") || strExtName.Equals(".xlsx"))
{
using (FileStream file = new FileStream(strFilePath, FileMode.Open, FileAccess.Read))
{
HSSFWorkbook workbook = new HSSFWorkbook(file);
ISheet sheet = workbook.GetSheetAt(iSheetIndex); //列头
foreach (ICell item in sheet.GetRow(sheet.FirstRowNum).Cells)
{
dt.Columns.Add(item.ToString(),typeof(string));
} //写入内容
System.Collections.IEnumerator rows = sheet.GetRowEnumerator();
while(rows.MoveNext())
{
IRow row = (HSSFRow)rows.Current;
if (row.RowNum == sheet.FirstRowNum)
{
continue;
} DataRow dr = dt.NewRow();
foreach (ICell item in row.Cells)
{
switch (item.CellType)
{
case CellType.Boolean:
dr[item.ColumnIndex] = item.BooleanCellValue;
break;
case CellType.Error:
dr[item.ColumnIndex] = ErrorEval.GetText(item.ErrorCellValue);
break;
case CellType.Formula:
switch (item.CachedFormulaResultType)
{
case CellType.Boolean:
dr[item.ColumnIndex] = item.BooleanCellValue;
break;
case CellType.Error:
dr[item.ColumnIndex] = ErrorEval.GetText(item.ErrorCellValue);
break;
case CellType.Numeric:
if (DateUtil.IsCellDateFormatted(item))
{
dr[item.ColumnIndex] = item.DateCellValue.ToString("yyyy-MM-dd hh:MM:ss");
}
else
{
dr[item.ColumnIndex] = item.NumericCellValue;
}
break;
case CellType.String:
string str = item.StringCellValue;
if (!string.IsNullOrEmpty(str))
{
dr[item.ColumnIndex] = str.ToString();
}
else
{
dr[item.ColumnIndex] = null;
}
break;
case CellType.Unknown:
case CellType.Blank:
default:
dr[item.ColumnIndex] = string.Empty;
break;
}
break;
case CellType.Numeric:
if (DateUtil.IsCellDateFormatted(item))
{
dr[item.ColumnIndex] = item.DateCellValue.ToString("yyyy-MM-dd hh:MM:ss");
}
else
{
dr[item.ColumnIndex] = item.NumericCellValue;
}
break;
case CellType.String:
string strValue = item.StringCellValue;
if (string.IsNullOrEmpty(strValue))
{
dr[item.ColumnIndex] = strValue.ToString();
}
else
{
dr[item.ColumnIndex] = null;
}
break;
case CellType.Unknown:
case CellType.Blank:
default:
dr[item.ColumnIndex] = string.Empty;
break;
}
}
dt.Rows.Add(dr);
}
}
} return dt;
}
Excel文件导成Datatable
MVC execl 导入导出的更多相关文章
- .NET MVC+angular导入导出
cshtml: <form class="form-horizontal" id="form1" role="form" ng-sub ...
- 2020-06-30 pol实现execl导入导出
1.导入依赖 <!-- 解析表格 --> <dependency> <groupId>org.apache.poi</groupId> <arti ...
- 基于NPOI的Execl导入导出例子
源地址:http://bbs.csdn.net/topics/390830774
- .Net MVC 导入导出Excel总结(三种导出Excel方法,一种导入Excel方法) 通过MVC控制器导出导入Excel文件(可用于java SSH架构)
.Net MVC 导入导出Excel总结(三种导出Excel方法,一种导入Excel方法) [原文地址] 通过MVC控制器导出导入Excel文件(可用于java SSH架构) public cl ...
- ASP.NET MVC5+EF6+EasyUI 后台管理系统(87)-MVC Excel导入和导出
本文示例代码下载: 链接:http://pan.baidu.com/s/1jHBdgCA 密码:hzh7 ps:Vs数据库脚本在解压目录下,修改web.config数据库链接,示例代码包含:导入,导出 ...
- 用MVC导入导出
导入导出对于刚做的人一脸懵逼,但是明白思路之后就感觉非常容易,我也是研究了好久,才总算做了出来,放在这里给大家分享一下 一.先看下导出 视图脚本 <script type ="text ...
- .NET导入导出Excel
若是开发后台系统,ASP.NET MVC中总是涉及了很多导入导出Excel的问题,有的时候处理起来比较烦 如果能使用以下代码解决,就完美了 public class ReportModel { [Ex ...
- NPOI导入导出Excel
.net mvc利用NPOI导入导出excel 注意:如何导出的提交方式ajax导出是失效的! 解决方案是:js处理l两个表单的提交 代码: 第一步. 在页面里面加入2个隐藏的iframe, 如下 ...
- ssm框架之将数据库的数据导入导出为excel文件
在这里首先我要将自己遇到的各种问题,以及需求记录下来,做一个备忘,便于以后查看: 需求:主要实现两个功能,将oracle数据库里的数据导出为excel,同时需要将excel表格的数据导入到数据库 环境 ...
随机推荐
- UWP_开源小程序 水印添加器
前几天写了一个确定水印位置的小博客.决定要写一个添加水印的UWP程序. 目前程序技术方面已经差不多了.所以提上日程
- 基于vue框架项目开发过程中遇到的问题总结(二)
1.mouseup事件丢失 查看了网上资料,造成mouseup事件丢失有两种原因: (1)触发了浏览器的drag事件 (2)由于鼠标离开了操作的区域,触发了mouseleave事件导致mouseup丢 ...
- phaser小游戏框架学习(一)
这两天由于项目的需要,所以简单学了一下phaser框架. 官网:http://phaser.io/ 还有一个phaser小站,是中文的网站,但是内容不如英文文档全,大家也可以去看这个网站,需要查阅AP ...
- django2集成DjangoUeditor富文本编辑器
富文本编辑器,在web开发中可以说是不可缺少的.django并没有自带富文本编辑器,因此我们需要自己集成,在这里推荐大家使用DjangoUeditor,因为DjangoUeditor封装了我们需要的一 ...
- luogu3380 树套树之线段树套线段树
个人感觉可能是最不需要脑子写的方法 不过也不太好调 就是用一个普通的线段树维护这个序列,但是对于线段树的每一个区间,再开一个动态开点的权值线段树,里面存储这个区间所有元素值 单点修改只会涉及到log棵 ...
- springdataRedis连接redis集群
配置文件: <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http:// ...
- 如何从GAC中复制DLL文件
运行执行:c:\Windows\assembly\gac_msil
- NETCore 调试
https://www.cnblogs.com/MingQiu/p/8227644.html https://www.cnblogs.com/shumin/p/9967854.html 前言 core ...
- n阶乘,位数,log函数,斯特林公式
一.log函数 头文件: #include <math.h> 使用: 引入#include<cmath> 以e为底:log(exp(n)) 以10为底:log10(n) 以m为 ...
- thinkphp自动验证和自动完成
tp验证码的自动验证小案例 模板文件 <form action="" method="post"> <p> User: <inpu ...