coreexcel导入导出

coreexcel导⼊导出
做的上⼀个项⽬⽤的是vs2013,传统的 Mvc模式开发的,excel报表的导⼊导出都是那⼏段代码,已经习惯了。
导⼊:
string filename = ExcelFileUpload.FileName;//获取Execle⽂件名
string savePath = Server.MapPath(("UploadExcel\\") + filename);//Server.MapPath 服务器上的指定虚拟路径相对应的物理⽂件路径
//savePath ="D:\vsproject\Projects\exceltestweb\exceltestweb\uploadfiles\test.xls"
//Response.Write(savePath);
DataTable ds = new DataTable();
ExcelFileUpload.SaveAs(savePath);//将⽂件保存到指定路径
DataTable dt = GetExcelDatatable(savePath);//读取excel数据
List<RegNumInfo> regList = ConvertDtToInfo(dt);//将datatable转为list
File.Delete(savePath);//删除⽂件
Response.Write("<script>alert('上传⽂件读取数据成功!');</script>");
导出:
HSSFWorkbook workbook = new HSSFWorkbook();//创建⼀个excel⽂件
ISheet sheet = workbook.CreateSheet("sheet1");//创建⼀个sheet
IRow row = null;//设置⾏
ICell cell = null;//设置单元格
//创建第⼀⾏
row = sheet.CreateRow(0);
//创建第⼀列
cell = row.CreateCell(0);
//给第⼀列赋值
cell.SetCellValue("类型");
//创建第⼆列
cell = row.CreateCell(1);
//给第⼆列赋值
cell.SetCellValue("数量");
msinfofor (int i = 0; i < listHouse.Count; i++)
{
row = sheet.CreateRow(i+1);//第⼏⾏
row.CreateCell(0).SetCellValue(listHouse[i].ParameterName);//第⼀个单元格
row.CreateCell(1).SetCellValue(listHouse[i].Count);//第⼆个单元格
// soure和count要和前台对应file
//var housepa = new { soure = listHouse[i].ParameterName, count = listHouse[i].Count };
//list.Add(housepa);
}
MemoryStream ms = new MemoryStream();//声明⼀个内存流
workbook.Write(ms);//将⽂件写⼊流中
context.Response.ContentType = "application/vnd.ms-excel";//输⼊的格式
//⽂件信息(⽂件头)attachment设置⽂件为打开保存对话框
context.Response.AddHeader("Content-Disposition",
"attachment;filename=" + HttpUtility.UrlEncode(type, System.Text.Encoding.UTF8) +
DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ".xls");
context.Response.BinaryWrite(ms.ToArray());//字节格式输⼊
context.Response.End();
workbook = null;
ms.Close();//关闭流
ms.Dispose();//释放资源
但是现在做项⽬我⽤的是vs2019 ,⽤ core 2.2 开发。在做导⼊导出报表的时候发现以前的模式不好使了,原因是指定路径的⽅法不能⽤了:Server.MapPath(),⽤ core 模式开发项⽬,也是刚接触怎末导⼊导出也不知道,那就只能问百度了。然后搜了⼀下,复制粘贴,修修改改很快就搞定了。
在core⾥要注册IHostingEnvironment 环境变量才能做excel的导⼊导出操作,(这⾥之说简单操作,如何封装就看个⼈了)
新建⼀个控制器,在控制器⾥直接注册就⾏了。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using SmartNet.Core;
using System.Data;
using Microsoft.AspNetCore.Http.Abstractions;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using System.IO;
using Newtonsoft.Json;
using SmartNet.Data;
using Microsoft.AspNetCore.Hosting;
using OfficeOpenXml;
using Microsoft.Azure.ActiveDirectory.GraphClient;
namespace SmartNet.Web.Areas.ProjectManage.Controllers
{
public class TaskController : ControllerBase
{
private IHostingEnvironment _hostingEnvironment;
public TaskController(IHostingEnvironment hostingEnvironment)
{
_hostingEnvironment = hostingEnvironment;
}
}
}
在做之前要下载插件:
装完插件后,⾸先是导⼊操作:
页⾯:
<div id="importBox" >
<form enctype="multipart/form-data" method="post" action="/####/####/Import">
<input type="file" name="excelfile" />
<input type="submit" value="导⼊" />
</form>
</div>
<script>
function TaiZhangExport() {
layer.open({
type: 1,
skin: 'layui-layer-rim', //加上边框
area: ['420px', '240px'], //宽⾼
content: $("#importBox").html()
});
}
</script>
 后台:
///<summary>
///公⽤路径
///</summary>
///<returns></returns>
private Tuple<string, string> GetTuple(string ExcelName)
{
string sWebRootFolder = _hostingEnvironment.WebRootPath;//获取根路径,core资源⽂件夹⼀般都在⽬录下,关于这块可以看我的 app接⼝⽂章,那⾥详细介绍了这块。
string sFileName = $"{ExcelName}.xlsx";
return Tuple.Create(sWebRootFolder, sFileName);
}
[HttpPost]
public IActionResult Import(IFormFile excelfile)
{
string sWebRootFolder = GetTuple("报表模板").Item1;
string sFileName = GetTuple("报表模板").Item2;
FileInfo file = new FileInfo(Path.Combine(sWebRootFolder, sFileName));
string[] FileType = excelfile.FileName.Split('.');
if (FileType[1] != "xlsx" && FileType[1] != "xls")
{
///financemanage/ledger/list
return Content("你导如的⽂件格式不正确,请导⼊excel⽂件格式(.xlsx,xls)");
}
if (!System.IO.Directory.Exists(sWebRootFolder + sFileName))//判断路径是否存在
{
file.Delete(); //删除服务器上的临时⽂件
}
try
{
//FileStream对象表⽰在磁盘或⽹络路径上指向⽂件的流。这个类提供了在⽂件中读写字节的⽅。
//Create:⽂件存在删除该⽂件,不存在创建新⽂件。
using (FileStream fs = new FileStream(file.ToString(), FileMode.Create))
{
excelfile.CopyTo(fs);
fs.Flush();
}
using (ExcelPackage package = new ExcelPackage(file))
{
StringBuilder sb = new StringBuilder();
ExcelWorksheet worksheet = package.Workbook.Worksheets[0];
int rowCount = worksheet.Dimension.Rows;
int ColCount = worksheet.Dimension.Columns;
bool isTrue = false;
/
/////////////////////////////////////////////////////////////////////////////////////
//注意在导⼊报表时,并不是能将导⼊就万事⼤吉了,要判断⼀下excel表⾥的数据是否和你要求的数据匹配,例如:时间数据,整型数据,浮点型数据,excel表中的每⼀列数据类型都要与你要求的每⼀列数据⾥类型匹配。
// 这时就需要我们⾃⼰在读取excel表中的数据时,⾃⼰去⼀个⼀个审查了。审查⼀般也有两种⽅式:
// 1,表中数据哪⼀⾏数据不通过,就过滤掉不通过的数据,通过的数据还按原⽅式导⼊,不通过的输出第⼏⾏,第⼏列的错误信息,⽐如:第⼆⾏,第三列,时间格式错误!(可以边判断边导⼊,⼀⾏通过就导⼊⼀⾏)
//  2,表中数据只要有⼀⾏不通过,整个表中的数据都不能导⼊,不通过的输出第⼏⾏,第⼏列的错误信息,⽐如:第⼆⾏,第三列,时间格式错误!(先判断后导⼊,就是先对整个表数据进⾏匹配,只要都通过了,才能导⼊)                  //  ⽐如我要导⼊的数据有四⾏,第⼀⾏时string,第⼆⾏是:int第三⾏是:float第四⾏是:datatime  格式是(2019/10/23)注意:时间格式要尽量定⼀个统⼀模式
for (int row = 2; row <= rowCount; row++)//在excel表中第⼀⾏是标题,所以数据是从第⼆⾏开始的。
{
for (int col = 1; col <= ColCount; col++)
{
if (col>1&&col<4)
{
if (worksheet.Cells[row, col].Value.ToString().Length == 0)//表中数据有可能是空,如果是字符格式就⽆所谓了,但是如果是整型或者浮点型,那就要判⼀下,给个默认值0了
{
worksheet.Cells[row, col].Value = 0;
}
if (!Regex.IsMatch(worksheet.Cells[row, col].Value.ToString(), @"^[+-]?\d*[.]?\d*$"))//⼤家知道,整型可以转浮点型,例如:float a  可以 a=1.0 也可以  a=1所以两个⼀块直接判断了。
{
if (isTrue == false)
{
sb.Append("导⼊⽂件失败!" + "\t");
sb.Append("        有⼀下错误:" + "\t");
}
sb.Append("第" + row + "⾏" + col + "列数据类型错误!" + "\t");
isTrue = true;
}
}
// Regex reg = new Regex(@"^(0[1-9]|1[0-2])/(0[1-9]|[12][0-9]|30|31)/([1-9]\d{3})$", RegexOptions.None | RegexOptions.IgnoreCase | RegexOptions.Multiline);
// MatchCollection mc = reg.Matches(worksheet.Cells[row, col].Value.ToString());
//^(?\d{2,4})/(?\d{1,2})/(?\d{1,2})$
if (col ==4)
{
if (SelectDateTime(worksheet.Cells[row, col].Value.ToString()))//判断时间格式在SelectDatatime⽅法中处理的,在下⾯
{
if (isTrue == false)
{
sb.Append("导⼊⽂件失败!" + "\t");
sb.Append("        有⼀下错误:" + "\t");
}
sb.Append("第" + row + "⾏" + col + "列时间格式类型错误!" + "\t");
isTrue = true;
}
}
}
sb.Append(Environment.NewLine);//重新起⼀⾏
}
if (isTrue == true)
{
return Content(sb.ToString());  //如果isture==true 说明有错误数据就直接返回错误数据,就不再进⾏导⼊操作了。
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
下⾯是,如果所有数据都匹配成功了,那就要执⾏导⼊操作了。
for (int row = 2; row <= rowCount; row++)
{
string第⼀个数据=worksheet.Cells[Row,1].Value.ToString(),
int第⼆个数据 = int.Parse(worksheet.Cells[Row,2].value.ToString()),
int第三个数据 =float.Parse(worksheet.Cells[Row,3].value.ToString()),
string第四个数据 =worksheet.Cells[Row,4].value.ToString(),
//下⾯就是如何把excel表中的数据插⼊数据库了,两种⽅式:1,数据⼀⾏⼀⾏插⼊。2,将数据存⼊DadaTable中整体存⼊。具体要看数据量了。
例如⼀⾏⼀⾏插⼊可以直接在for循环中直接插⼊就⾏了。
--插⼊的sql语句
--存储过程名
}
file.Delete();//删除刚创建的临时⽂件。
return Redirect("/ReportManage/Finance_CostNoTower/List");
}
}
catch (Exception ex)
{
return Content(ex.Message);
}
}
public bool SelectDateTime(string strtime)
{
try
{
DateTime.Parse(strtime);//笼统的判断字符串格式是否是时间格式
}
catch
{
return true;
}
string StrTime = strtime;
//判断系统读取的时间格式是否和⽂件中的时间格式⼀致
/
/例如⽂件上时间格式是"2019/07"⽽系统读取格式是:"2019/07/01 星期⼀ 0:00:00"
if (strtime.Length > 7)
{
//如果不⼀致,取第⼀个空格前的字符串。
StrTime = strtime.Substring(0, strtime.IndexOf(''));
}
//系统定义excel⽂件中时间格式是"2019/07"或者"2019/7"如果是其它格式则认为是错误时间格式。
if (!StrTime.Contains('/'))
{
return true;
}
return false;
}
导⼊的基本过程也就这些了。下⾯是导出,导出就相对容易多了,不需要在进⾏数据匹配了。
页⾯:
<button class="layui-btn" onclick="Import()">
导出数据
</button>
<script>
function Import() {
location.href = "/ReportManage/Finance_CostNoTower/Export?" +传⼊的参数
}
</script>
  后台:
public IActionResult Export()
{
DataTable dtList=获取数据库数据的⽅法(参数);
string sWebRootFolder = GetTuple("报表模板").Item1;
string sFileName = GetTuple("报表模板").Item2;
FileInfo file = new FileInfo(Path.Combine(sWebRootFolder, sFileName));//创建⼀个FileInfo实例,创建路径
if (!System.IO.Directory.Exists(sWebRootFolder + sFileName))//⽂件是否存在如果存在删掉⽂件重新创建。
{
file.Delete(); //删除服务器上的临时⽂件
}
using (ExcelPackage package = new ExcelPackage(file))//创建excel
{
// 添加worksheet
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("aspnetcore");
//worksheet.Cells.Style.ShrinkToFit = true;//单元格⾃动适应⼤⼩
for (int i = 1; i < 4; i++)
{
worksheet.Column(i).Width = 25;//设置列宽
}
//添加头
worksheet.Cells[1, 1].Value = "excel表格第⼀列标题";
worksheet.Cells[1, 2].Value = "excel表格第⼆列标题";
worksheet.Cells[1, 3].Value = "excel表格第三列标题";
worksheet.Cells[1, 4].Value = "excel表格第四列标题";
if (dtList != null && dtList.Rows.Count > 0)
{
//添加值
int Count = 1;
for (int i = 0; i < dtList.Rows.Count; i++)
{
Count++;
DataRow item = dtList.Rows[i];//创建⾏
worksheet.Cells[Count, 1].Value = item[数据库中数据参数名].ToString();
worksheet.Cells[Count, 2].Value = item[数据库中数据参数名].ToString();
worksheet.Cells[Count, 3].Value = item[数据库中数据参数名].ToString();
worksheet.Cells[Count, 4].Value = item[数据库中数据参数名].ToString();
}
}
package.Save();//保存
}
return File(sFileName, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "导出数据.xlsx");//导出excel表格        }
好了,到这⾥excel报表的导⼊导出就介绍完了。希望对⼀些朋友有些帮助。

本文发布于:2024-09-21 14:53:16,感谢您对本站的认可!

本文链接:https://www.17tex.com/tex/1/380267.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:数据   格式   路径   时间   导出   错误   报表   判断
留言与评论(共有 0 条评论)
   
验证码:
Copyright ©2019-2024 Comsenz Inc.Powered by © 易纺专利技术学习网 豫ICP备2022007602号 豫公网安备41160202000603 站长QQ:729038198 关于我们 投诉建议