基于MVC模式的Excel数据迁移框架研究与实现
- 格式:pdf
- 大小:732.86 KB
- 文档页数:5
MVC导⼊Excel⽂件(完整版)View视图部分:<form method="post" enctype="multipart/form-data" action="/Position/ImportExcel" class="form-group"><input name="file" type="file" id="file" /><button id="btn_import" type="submit" class="btn btn-info"><span class="glyphicon glyphicon-pencil"></span>导⼊</button></form>控制器部分:public ActionResult ImportExcel(){//获取上传的Excel⽂件HttpPostedFileBase File = Request.Files["file"];string message = "";if (File.ContentLength > 0){//GetExtension:返回指定路径的⽂件的扩展名var Isxls = System.IO.Path.GetExtension(File.FileName).ToString().ToLower();if (Isxls != ".xls" && Isxls != ".xlsx"){message = "<script>alert('请上传Excel⽂件'),window.location.href='/Position/Index'</script>";}var FileName = File.FileName;//获取⽂件夹名称var path = Server.MapPath("~/FileExcel/" + FileName);File.SaveAs(path);//将⽂件保存到服务器PositionBLL bll = new PositionBLL();var list = bll.FileUpLoad(path);if (list.Count > 0){int num = bll.LoadFile(list);if (num > 0){message = "<script>alert('数据导⼊成功'),window.location.href='/Position/Index'</script>";}}else{message = "<script>alert('导⼊的数据不能为空'),window.location.href='/Position/Index'</script>";}}else{message = "<script>alert('请选择上传的⽂件'),window.location.href='/Position/Index'</script>";}return Content(message);}Model部分:public class PositionModel{string PositionName;string Qualification;string Remark;public string PositionName1 { get => PositionName; set => PositionName = value; }public string Qualification1 { get => Qualification; set => Qualification = value; }public string Remark1 { get => Remark; set => Remark = value; }}PositionBLL部分:public class PositionBLL{//private const string ConnString2003 = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel8.0';HDR='Yes'";//链接打开excel的字符串private const string ConnString2003 = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 8.0';"; public List<PositionModel> FileUpLoad(string filePath){DataSet ds = new DataSet();List<PositionModel> list = new List<PositionModel>();string strSQL = string.Format(ConnString2003, filePath);//OleDbConnection:表⽰与数据源的开放链接OleDbConnection conn = new OleDbConnection(strSQL);try{//判断连接的状态if (conn.State == ConnectionState.Broken || conn.State == ConnectionState.Closed){conn.Open();}DataTable tableName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);//获取Excel的第⼀个Sheet名称var sheetName = tableName.Rows[0]["TABLE_NAME"].ToString().Trim();string SQL = "select * from [" + sheetName + "]";OleDbDataAdapter sa = new OleDbDataAdapter(SQL, conn);sa.Fill(ds);foreach (DataRow dr in ds.Tables[0].Rows){PositionModel model = new PositionModel();model.PositionName1 = dr["职位名称"].ToString();model.Qualification1 = dr["任职资格"].ToString();model.Remark1 = dr["职位描述"].ToString();list.Add(model);}}catch (Exception ex){Console.WriteLine("错误信息:PositionBLL+FileUpLoad⽅法" + ex);}return list;}//将数据循环遍历到数据库中PositionDAL dal = new PositionDAL();public int LoadFile(List<PositionModel> list){var num = 0;foreach (var item in list){PositionModel model = new PositionModel();model.PositionName1 = item.PositionName1;model.Qualification1 = item.Qualification1;model.Remark1 = item.Remark1;num = dal.Add(model);}return num;}PositionDAL部分:using System;using System.Collections.Generic;using System.Linq;using System.Web;namespace ExcleImport.Models{public class PositionDAL{DBhelper dBhelper = new DBhelper();public int Add(PositionModel model) {string sql = string.Format("insert into userInfo (position,grade,remark)values('{0}','{1}','{2}')", model.PositionName1, model.Qualification1, model.Remark1);return dBhelper.ExceDml(sql);}}}DBhelper部分://创建链接数据库的字符串string dbStr = "Data Source=.;Initial Catalog=sales;Integrated Security=True";public int ExceDml(string sql){try{int res = 0;//连接数据库using (SqlConnection conn = new SqlConnection(dbStr)){//打开连接数据库conn.Open();//执⾏sqlSqlCommand comm = new SqlCommand(sql, conn);res = comm.ExecuteNonQuery();}return res;}catch (Exception ex){Console.WriteLine("错误信息:DBhelper+ExceDml⽅法" + ex);throw ex;}}数据库表:create table userInfo(id int identity(1,1)not null,position varchar(50)not null,grade varchar(50)not null,remark varchar(100)not null)。
Excel数据导入和导出技巧利用外部数据连接和数据表实现数据集成在日常工作和生活中,我们常常需要处理大量的数据,而Excel作为一款功能强大的电子表格软件,提供了丰富的数据导入和导出技巧,能够帮助我们高效地进行数据集成和分析。
本文将介绍如何利用外部数据连接和数据表来实现Excel数据导入和导出的技巧,帮助读者更好地利用Excel进行数据处理。
一、外部数据连接外部数据连接是指将Excel与其他数据源进行关联,通过连接来获取和更新外部数据。
Excel提供了多种外部数据连接的方式,包括从文本文件导入、从数据库导入、从Web导入等。
下面将介绍两种常用的外部数据连接技巧。
1. 从文本文件导入数据在Excel中,我们可以通过“数据”选项卡中的“从文本”命令来导入文本文件中的数据。
具体操作步骤如下:(1)点击“数据”选项卡,在“获取外部数据”组中选择“从文本”。
(2)选择待导入的文本文件,并点击“打开”按钮。
(3)根据导入文本文件的格式,按照向导完成导入设置,包括分隔符、数据格式等。
(4)点击“确定”按钮即可完成数据导入。
2. 从数据库导入数据在Excel中,我们还可以通过“数据”选项卡中的“从其他来源”命令来导入数据库中的数据。
具体操作步骤如下:(1)点击“数据”选项卡,在“获取外部数据”组中选择“从其他来源”。
(2)选择要连接的数据库类型,如SQL Server、Access等,并点击“下一步”按钮。
(3)按照向导完成数据库连接设置,包括服务器地址、数据库名称等。
(4)选择要导入的数据表或查询,并点击“下一步”按钮。
(5)根据需要选择导入数据的方式和设置,如导入数据到现有工作表、导入数据到新的工作簿等。
(6)点击“完成”按钮即可完成数据导入。
二、数据表的使用数据表是Excel中的一种特殊对象,它能够快速地对数据进行排序、筛选、汇总等操作。
通过利用数据表,我们可以更加方便地进行数据集成和分析。
下面将介绍两种常用的数据表技巧。
前几天一个MVC3.0项目做了一个Excel导出功能,今天来记录一下. 采取了最简单的方法.用的是Html拼接成Table表格的方式,返回 FileResult 输出一个二进制的文件.第一种:使用FileContentResult//// 摘要:// 通过使用文件内容,内容类型,文件名称创建一个FileContentResult对象//// 参数:// fileContents:// 响应的二进制文件内容//// contentType:// 内容类型(MIME类型)//// fileDownloadName:// 显示在浏览器下载窗口的文件名称//// 返回结果:// 文件内容对象.protected internal virtual FileContentResult File(byte[] fileContents, string contentType, string fileDownloadName);需要将文件内容转化成字节数组byte[]byte[] fileContents = Encoding.Default.GetBytes(sbHtml.ToString());第二种:使用FileStreamResult// 其他参数描述同FileContentResult// 参数:// fileStream:// 响应的流//// 返回结果:// 文件流对象.protected internal virtual FileStreamResult File(Stream fileStream, string contentType, string fileDownloadName);需要将文件内容转化成流varfileStream = new MemoryStream(fileContents);第三种:使用FilePathResult// 其他参数描述同FileContentResult// 参数:// fileName:// 响应的文件路径//// 返回结果:// 文件流对象.protected internal virtual FilePathResult File(string fileName, string contentType, string fileDownloadName);服务器上首先必须要有这个Excel文件,然会通过Server.MapPath获取路径返回.具体详情请看代码.1 public FileResultExportExcel()2 {3 varsbHtml = new StringBuilder();4 sbHtml.Append("<table border='1' cellspacing='0' cellpadding='0'>");5 sbHtml.Append("<tr>");6 varlstTitle = new List<string> { "编号", "姓名", "年龄", "创建时间" };7 foreach (var item in lstTitle)8 {9 sbHtml.AppendFormat("<td style='font-size:14px;text-align:center;background-color: #DCE0E2; font-weight:bold;' height='25'>{0}</td>", item);10 }11 sbHtml.Append("</tr>");1213 for (inti = 0; i< 1000; i++)14 {15 sbHtml.Append("<tr>");16 sbHtml.AppendFormat("<td style='font-size:12px;height:20px;'>{0}</td>", i);17 sbHtml.AppendFormat("<td style='font-size:12px;height:20px;'>屌丝{0}号</td>", i);18 sbHtml.AppendFormat("<td style='font-size:12px;height:20px;'>{0}</td>", new Random().Next(20, 30) + i);19 sbHtml.AppendFormat("<td style='font-size:12px;height:20px;'>{0}</td>", DateTime.Now);20 sbHtml.Append("</tr>");21 }22 sbHtml.Append("</table>");2324 //第一种:使用FileContentResult25 byte[] fileContents =Encoding.Default.GetBytes(sbHtml.ToString());26 return File(fileContents, "application/ms-excel", "fileContents.xls");2728 //第二种:使用FileStreamResult29 varfileStream = new MemoryStream(fileContents);30 return File(fileStream, "application/ms-excel", "fileStream.xls");3132 //第三种:使用FilePathResult33 //服务器上首先必须要有这个Excel文件,然会通过Server.MapPath获取路径返回.34 varfileName = Server.MapPath("~/Files/fileName.xls");35 return File(fileName, "application/ms-excel", "fileName.xls");36 }。
利用Excel进行数据迁移和数据转换在日常工作和生活中,我们经常需要进行数据的迁移和转换。
而使用Excel软件,可以帮助我们高效、准确地完成这些任务。
本文将介绍如何利用Excel进行数据迁移和数据转换,以及一些常用的技巧和注意事项。
一、利用Excel进行数据迁移数据迁移是将数据从一个地方转移到另一个地方的过程。
在Excel 中,我们可以通过以下步骤来进行数据迁移:1. 打开Excel软件,并新建一个工作表。
2. 将原始数据复制到工作表中的合适位置。
可以使用快捷键Ctrl+C复制数据,然后在Excel中使用Ctrl+V粘贴数据。
3. 如果需要对数据进行整理和清洗,可以利用Excel的强大功能来实现。
例如,可以使用筛选、排序、条件格式等功能对数据进行处理,使其更加规范和易读。
4. 如果需要在迁移的过程中对数据进行转换,可以使用Excel的公式功能。
例如,可以使用VLOOKUP函数实现数据匹配和替换,使用IF函数实现条件判断和计算等。
二、利用Excel进行数据转换数据转换是将数据的格式或结构进行调整,以满足特定的需求。
在Excel中,我们可以通过以下步骤来进行数据转换:1. 打开Excel软件,并导入需要进行数据转换的文件。
可以使用Excel的打开功能或者拖拽文件到Excel窗口来实现。
2. 在Excel中选择需要转换的数据,可以使用鼠标拖动选中数据范围,或者使用快捷键Ctrl+A选择全部数据。
3. 在Excel的数据选项卡中,可以找到一些常用的数据转换功能。
例如,可以使用文本到列功能将一个单元格中的文本分割到多个单元格中,使用合并单元格功能将多个单元格合并为一个单元格,使用转置功能将行列进行互换等。
4. 如果需要进行更加复杂的数据转换,可以使用Excel的宏编程功能。
通过录制宏和编写宏代码,可以实现自定义的数据转换流程。
三、常用技巧和注意事项在利用Excel进行数据迁移和数据转换的过程中,有一些常用的技巧和注意事项:1. 确保数据的准确性:在进行数据迁移和数据转换之前,需要对原始数据进行审查和清理,确保数据的准确性和完整性。
Excel数据导入导出技巧实现数据的快速迁移在Excel数据处理中,数据的导入和导出是非常常见且重要的操作。
合理运用数据导入导出技巧不仅可以提升工作效率,还可以实现数据的快速迁移。
本文将介绍几种Excel数据导入导出技巧,帮您快速掌握这些技巧。
第一、Excel数据导入技巧Excel提供了多种方式来导入外部数据,下面将介绍两种常用的数据导入方法。
1. 从文本文件导入数据在Excel中,可以通过“数据”选项卡上的“从文本”按钮来导入文本文件中的数据。
点击“从文本”按钮后,选择要导入的文本文件并按照向导进行设置,即可将文本文件中的数据导入到Excel中。
这种方法适用于以文本形式保存数据的情况,比如以逗号、制表符或其他特定字符分隔的数据。
导入后,Excel会根据分隔符将数据自动划分到不同的列中,便于后续的数据处理和分析。
2. 从数据库导入数据如果您的数据存储在数据库中,可以通过Excel与数据库进行连接来实现数据的快速导入。
在Excel的“数据”选项卡上选择“从其他来源”中的“从SQL Server”或“从Access”等选项,根据向导的提示配置数据库连接参数和查询条件,即可将数据库中的数据导入到Excel中。
这种方法适用于需要频繁从数据库中导入数据并进行处理的情况,通过与数据库的连接,可以实现数据的即时更新和实时查询。
第二、Excel数据导出技巧除了数据导入,Excel也提供了多种方式来导出数据,下面将介绍两种常用的数据导出方法。
1. 将Excel数据导出为文本文件在Excel中,可以选择需要导出的数据范围,然后点击“文件”选项卡的“另存为”按钮,在保存类型中选择“文本(制表符分隔)”或其他类型,即可将Excel数据导出为文本文件。
这种方法适用于将Excel中的数据导出到其他系统或软件进行进一步处理的情况。
导出的文本文件可以以制表符或其他字符作为分隔符,方便其他系统或软件进行数据导入和处理。
2. 将Excel数据导出为CSV文件CSV(逗号分隔值)文件是一种常见的数据导出格式,可以在Excel中将数据导出为CSV文件。
Excel数据导入与导出快速实现数据迁移和共享在当今信息化的社会中,数据处理与管理已经成为各个领域的重要工作。
Excel作为一款功能强大、易于操作的电子表格软件,被广泛应用于数据处理、分析和可视化展示等方面。
其中,Excel的数据导入与导出功能更是实现数据迁移和共享的重要手段。
本文将介绍如何快速实现Excel数据导入与导出,以及其在数据迁移和共享方面的作用。
一、Excel数据导入Excel提供了多种导入数据的方式,可以根据不同需求选择适合的方法。
1. 手动输入导入:对于少量数据或者需要即时录入的情况,可以直接在Excel中手动输入数据。
通过在单元格中输入数据,或者复制粘贴数据到单元格中,即可完成数据导入。
2. 使用文本导入向导:如果需要导入大量的文本数据,可以使用Excel的"文本导入向导"功能。
首先,将文本数据保存为.txt、.csv等格式;然后,通过"数据"选项卡的"来自文本"命令打开"文本导入向导";最后,按照向导提示进行设置和导入数据。
3. 使用外部数据源导入:Excel还支持从外部数据源中导入数据,例如数据库、Web页面、XML文件等。
通过"数据"选项卡中的"获取外部数据"命令,可以选择合适的数据源,并按照提示进行设置和导入数据。
二、Excel数据导出Excel提供了多种导出数据的方式,可以将数据保存为不同格式的文件,方便数据的共享和传输。
1. 保存为本地文件:通过"文件"选项卡的"另存为"命令,可以将Excel表格保存为本地文件。
可以选择保存为Excel工作簿、CSV文件、PDF文件等不同格式,根据需要选择合适的格式进行保存。
2. 导出为数据库文件:对于需要将Excel数据导入到数据库中的情况,可以将Excel数据导出为数据库文件。
后端Springboot前端VUE实现Excel导⼊功能功能描述:做的是物联⽹的项⽬,Excel导⼊实现的功能是将Excel中的数据批量的导⼊AEP系统,再导⼊我们系统中。
⽬前已经完成该功能,前端还会添加进度条优化。
对于导⼊导出功能,推荐这个Git:Excel模板:前端向后端传递的参数:前端代码:<Uploadname="wlwDeviceFile"ref="upload":action="pathUrl":on-success="handleSuccess":on-error="handleError":format="['xls','xlsx']":max-size="5120":on-format-error="handleFormatError":on-exceeded-size="handleMaxSize":before-upload="handleBeforeUpload":data="extraData":disabled="!isLock"><Button type="primary">选择⽂件</Button></Upload>data() {return {isLock: true,mesg: false,extraData: {aepProductId: localStorage.productId,productId: localStorage.productItemId,projectId: localStorage.currentProjectId},mes: "",cod: 0,// currentShow: false,pathUrl: Util.baseUrl + "/api/excel/import",wlwDevice: {fileName: "", //⽤于显⽰上传⽂件名id: localStorage.productId,autoSubscribe: 0},ruleValidate: {fileName: [{required: true,message: "请选择⽂件",trigger: "change"}]}};},handleSuccess(res, file) {// console.log("res++++++++++++++++++++++++++", res);if (res.code == 0) {this.cod = res.code;this.mes = '导⼊成功';console.log(this.$refs.upload.fileList);// this.$refs.upload.fileList.splice(0, 1);} else {this.cod = res.code;this.mes = res.message;}this.isLock = true;// this.$Spin.hide();this.wlwDevice.fileName = ;if (this.$refs.upload.fileList.length > 1) {this.$refs.upload.fileList.splice(0, 1);}// this.$emit("cancel", this.isOpen);},handleSubmit(name) {console.log("----------------------");this.$refs[name].validate(valid => {if (valid) {this.mesg = true;this.$refs[name].resetFields();this.$emit("cancel", this.isOpen);this.$emit("refreshList");console.log("-------------@@@--------");} else {后端解析 Excel,将数据读取出来导⼊AEP系统导⼊我们系统:后端代码:导⼊POM依赖:<dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>3.9</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml-schemas</artifactId><version>3.9</version></dependency>解析Excel的⽅法:@Component@NoArgsConstructorpublic class ParseExcelUtil {private static final Logger log = LoggerFactory.getLogger(ParseExcelUtil.class);public static Workbook getWorkbook(InputStream is, String fileName) throws ExcelIOException {Workbook workbook = null;String fileType = fileName.substring(stIndexOf("."));// 推荐使⽤poi-ooxml中的WorkbookFactory.create(is)来创建Workbook,// 因为HSSFWorkbook和XSSFWorkbook都实现了Workbook接⼝(可以解决以下报错问题)try {if (ExcelVersion.V2003.getSuffix().equals(fileType)) {workbook = new HSSFWorkbook(is);} else if (ExcelVersion.V2007.getSuffix().equals(fileType)) {workbook = new XSSFWorkbook(is);}}catch (IOException e){// ⽆效后缀名称,这⾥之能保证excel的后缀名称,不能保证⽂件类型正确,不过没关系,在创建Workbook的时候会校验⽂件格式 throw new ExcelIOException("请上传⽂件!");}return workbook;}}Excel版本问题的枚举:@NoArgsConstructorpublic enum ExcelVersion {/*** 虽然V2007版本⽀持最⼤⽀持1048575 * 16383 ,* V2003版⽀持65535*255* 但是在实际应⽤中如果使⽤如此庞⼤的对象集合会导致内存溢出,* 因此这⾥限制最⼤为10000*100,如果还要加⼤建议先通过单元测试进⾏性能测试。
Java解析Excel⽂件并把数据存⼊数据库前段时间做⼀个⼩项⽬,为了同时存储多条数据,其中有⼀个功能是解析Excel并把其中的数据存⼊对应数据库中。
花了两天时间,不过⼀天多是因为⽤了"upload"关键字作为URL从⽽导致总报同⼀个错,最后在同学的帮助下顺利解决,下⾯我把⾃⼰⽤"POI"解析的⽅法总结出来供⼤家参考(我⽤的是SpingMVC和hibernate框架)。
1.web.xml中的配置⽂件web.xml中的配置⽂件就按照这种⽅式写,只需要把"application.xml"换成你的配置⽂件名即可<!--⽂件上传对应的配置⽂件--><listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener><context-param><param-name>contextConfigLocation</param-name><param-value>classpath:application.xml</param-value></context-param>2.application.xml的配置⽂件(固定写发)在这个配置⽂件中你还可以规定上传⽂件的格式以及⼤⼩等多种属性限制<!-- 定义⽂件上传解析器 --><bean id="multipartResolver"class="monsMultipartResolver"></bean>3.⽂件上传的前端HTML注意:1.enctype="multipart/form-data" 必须写,封装表单2.method="post",提交⽅式必须为"post"提交3.action="${text}/uploadfile", "uploadfile"切记不要写成"upload",否则你找到世界末⽇也不会找到哪⾥有问题(本⼈因为这个折腾了⼀天多时间)。
基于springMVC 和mybatis的Excel数据导出废话不多说,直接上代码:1、Action@RequestMapping("/deriveOrder")public void deriveOrder(OrderInfoosModel model,HttpServletRequest request,HttpServletResponse response) throws Exception{//找出所有已退货订单List<Integer> orderList = orderInfoosService.findBySelective(model);if(orderList == null || orderList.isEmpty()){sendFailureMessage(response, "没有要导出的订单。
");return;}//生成excel 并返回文件路径String filePath = orderInfoosService.downloadOrder(model,orderList);//输出文件response.setCharacterEncoding("utf-8");response.setContentType("multipart/form-data");SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");String ctxPath = "已退货-" + sdf.format(new Date(System.currentTimeMillis())).toString() + ".xls";response.setHeader("Content-Disposition", "attachment;fileName="+ctxPath);OutputStream os = null;InputStream inputStream = null;try {File file=new File(filePath);System.out.println(file.getAbsolutePath());inputStream=new FileInputStream(file);os=response.getOutputStream();byte[] b=new byte[1024];int length;while((length=inputStream.read(b))>0){os.write(b,0,length);}} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally{try {if(os!=null){os.flush();}if(inputStream!=null){inputStream.close();}} catch (Exception e) {}}}2、servicepublic String downloadOrder(OrderInfoosModel model,List<Integer> orderList) throws IOException, WriteException {File ctxFile = new File(SUPPLIER_ORDERS_UPLOAD_PATH);if (!ctxFile.isDirectory()) {ctxFile.mkdirs();}// 文件的存储的相对路径SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");String ctxPath = "订单-" + sdf.format(new Date()).toString() + ".xls";String filePath = SUPPLIER_ORDERS_UPLOAD_PA TH + ctxPath;// 新建立一个jxl文件,即在e盘下生成testJXL.xlsOutputStream os = new FileOutputStream(filePath);WritableWorkbook wwb = Workbook.createWorkbook(os);WritableSheet sheet = wwb.createSheet("全部订单", 0);Label label = null;createHead(label, sheet);List<OrderInfoosBean> dataList = mapper.findAllByModel(model);createData(label, sheet, dataList);// 分类int n = 1;for (int i = 0; i < orderList.size(); i++) {model.setId(orderList.get(i));dataList = mapper.findAllByModel(model);sheet = wwb.createSheet(dataList.get(0).getWareHouseName(), n);createHead(label, sheet);createData(label, sheet, dataList);n++;}wwb.write();// 关闭文件wwb.close();os.close();return filePath;}private void createData(Label label, WritableSheet sheet,List<OrderInfoosBean> dataList) throws RowsExceededException, WriteException {for (int i = 0; i < dataList.size(); i++) {OrderInfoosBean bean = dataList.get(i);setData(label, sheet, bean, i + 1);}}private void setData(Label label, WritableSheet sheet,OrderInfoosBean bean, int i) throws RowsExceededException, WriteException { WritableFont wf = new WritableFont(WritableFont.TIMES, 11,WritableFont.NO_BOLD, false);WritableCellFormat wc = new WritableCellFormat(wf);setColor(wc, bean.getStatus());//编号label = new Label(0, i, bean.getId() + "", wc);sheet.addCell(label);//"代理名"String proxyName=bean.getProxyName();if(proxyName==null){proxyName="";}label = new Label(1, i, proxyName,wc);sheet.addCell(label);//"订单日期",SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");label = new Label(2, i, sdf.format( bean.getCreated()).toString(),wc);sheet.addCell(label);// "货源",String wareHouseName= bean.getWareHouseName();if(wareHouseName==null){wareHouseName="";}label = new Label(3, i,wareHouseName,wc);sheet.addCell(label);// "快递名称",String delivery= bean.getDelivery();if(delivery==null){delivery="";}label = new Label(4, i, delivery.toString(),wc);sheet.addCell(label);// "货号",label = new Label(5, i, bean.getArticleno().toString(),wc);sheet.addCell(label);// "尺码",String Size= bean.getSize();if(Size==null){Size="";}label = new Label(6, i,Size,wc);sheet.addCell(label);// "市场价",label = new Label(7, i, bean.getMarketprice().toString(),wc);sheet.addCell(label);// "折扣",double Discount=bean.getDiscount();label = new Label(8, i, Discount+"",wc);sheet.addCell(label);// "付款金额",label = new Label(9, i, bean.getPrice().toString()+"",wc);sheet.addCell(label);// "运费",double postage = bean.getPostage();label = new Label(10, i, postage+"",wc);sheet.addCell(label);// "收件人姓名",String Addressee= bean.getAddressee();if(Addressee==null){Addressee="";}label = new Label(11, i, Addressee,wc);sheet.addCell(label);// "订单状态"String Status= bean.getStatus();if(Status==null){Status="";}if(Status.equals("01")){Status = "待付款";}else if(Status.equals("02")){Status = "已付款";}else if(Status.equals("04")){Status = "反馈失败";}else if(Status.equals("05")){Status = "反馈成功";}else if(Status.equals("06")){Status = "配货中";}else if(Status.equals("08")){Status = "审核通过";}else if(Status.equals("10")){Status = "待退款";}else if(Status.equals("11")){Status = "已退货";}else if(Status.equals("12")){Status = "已退款";}label = new Label(12, i,Status,wc);sheet.addCell(label);//联系电话String mobile = bean.getMobile();if(mobile==null){mobile="";}label = new Label(13, i,mobile,wc);sheet.addCell(label);//收件地址String address = bean.getAddress();if(address==null){address="";}label = new Label(14, i,address,wc);sheet.addCell(label);}private void setColor(WritableCellFormat wc, String status) throws WriteException { if(status.equals("01")){wc.setBackground(jxl.format.Colour.AQUA);}else if(status.equals("02")){wc.setBackground(jxl.format.Colour.ROSE);}else if(status.equals("04")){wc.setBackground(jxl.format.Colour.ORANGE);}else if(status.equals("05")){wc.setBackground(jxl.format.Colour.PINK);}else if(status.equals("06")){wc.setBackground(jxl.format.Colour.GOLD);}else if(status.equals("08")){wc.setBackground(jxl.format.Colour.LIME);}else if(status.equals("10")){wc.setBackground(jxl.format.Colour.GREEN);}else if(status.equals("11")){wc.setBackground(jxl.format.Colour.YELLOW);}else if(status.equals("12")){wc.setBackground(jxl.format.Colour.BLUE);}}private void createHead(Label label, WritableSheet sheet) throws WriteException { String[] title = { "编号", "代理名", "订单日期", "货源", "快递名称", "货号", "尺码", "市场价","折扣", "付款金额", "运费", "收件人姓名", "订单状态","联系电话","收件地址"};WritableFont wf = new WritableFont(WritableFont.TIMES, 11,WritableFont.NO_BOLD, false);WritableCellFormat wc = new WritableCellFormat(wf);wc.setBackground(jxl.format.Colour.WHITE);for (int i = 0; i < title.length; i++) {label = new Label(i, 0, title[i]);sheet.addCell(label);}label = new Label(18, 01, "待付款");sheet.addCell(label);label = new Label(18, 02, "已付款");sheet.addCell(label);label = new Label(18, 04, "反馈失败");sheet.addCell(label);label = new Label(18, 05, "反馈成功");sheet.addCell(label);label = new Label(18, 06, "配货中");sheet.addCell(label);label = new Label(18, 8, "审核通过");sheet.addCell(label);label = new Label(18, 10, "待退货");sheet.addCell(label);label = new Label(18, 11, "已退货");sheet.addCell(label);label = new Label(18, 12, "已退款");sheet.addCell(label);wc = new WritableCellFormat(wf);wc.setBackground(jxl.format.Colour.AQUA); label = new Label(17, 01, "",wc);sheet.addCell(label);wc = new WritableCellFormat(wf);wc.setBackground(jxl.format.Colour.ROSE); label = new Label(17, 02, "",wc);sheet.addCell(label);wc = new WritableCellFormat(wf);wc.setBackground(jxl.format.Colour.ORANGE); label = new Label(17, 04, "",wc);sheet.addCell(label);wc = new WritableCellFormat(wf);wc.setBackground(jxl.format.Colour.PINK); label = new Label(17, 05, "",wc);sheet.addCell(label);wc = new WritableCellFormat(wf);wc.setBackground(jxl.format.Colour.GOLD); label = new Label(17, 06, "",wc);sheet.addCell(label);wc = new WritableCellFormat(wf);wc.setBackground(jxl.format.Colour.LIME); label = new Label(17, 8, "",wc);sheet.addCell(label);wc = new WritableCellFormat(wf);wc.setBackground(jxl.format.Colour.GREEN);label = new Label(17, 10, "",wc);sheet.addCell(label);wc = new WritableCellFormat(wf);wc.setBackground(jxl.format.Colour.YELLOW);label = new Label(17, 11, "",wc);sheet.addCell(label);wc = new WritableCellFormat(wf);wc.setBackground(jxl.format.Colour.BLUE);label = new Label(17, 12, "",wc);sheet.addCell(label);}/*** 根据条件查询数据* @param model* @return*/public List<Integer> findBySelective(OrderInfoosModel model) { // TODO Auto-generated method stubreturn mapper.findBySelective(model);}3、jsfunction deriveOrder(){var wareHouseName=$("input[name='wareHouseName']").val();var articleno=$("input[name='articleno']").val();var addressee=$("input[name='addressee']").val();var startTime =$("input[name='startTime']").val();var endsTime =$("input[name='endsTime']").val();var status =$("input[name='status']").val();var data = "wareHouseName="+wareHouseName+"&articleno="+articleno+"&startTime="+startTime+"&endsTime="+endsTime+"&status="+status;var link = "deriveOrder.do"+'?'+data;window.open(link);}4、jsp<a href="javascript:void(0)" class="easyui-linkbutton" onclick="deriveOrder();">导出订单</a>至此,excel表格可以导出下面是效果图:。
vue+springmvc导出excel数据的实现代码vue端处理this.$http.get(this.service + '/user/excel',{responseType: 'blob'}).then(({data})=> {(typeof data)var a = document.createElement('a');var url = window.URL.createObjectURL(data);a.href = url;a.download = '⽤户统计信息.xls';a.click();window.URL.revokeObjectURL(url);})web端处理int total=userBsService.getCount(null);List<UserVo> list=userBsService.getList(null, 1, total);String fileName = new Date().getTime() + "";XSSFWorkbook wb=new XSSFWorkbook();Sheet sheet=wb.createSheet();Row row0=sheet.createRow(0);String titleName[] = {"⽤户账号", "充值总⾦额", "邀请总⼈数", "社群组"};//列名for(int i=0;i<titleName.length;i++){sheet.setColumnWidth(i, 10 * 512);row0.createCell(i).setCellValue(titleName[i]);}int i=0;for(UserVo v:list){Row row=sheet.createRow(i+1);if(!StringUtils.isEmpty(v.getMobile())){row.createCell(0).setCellValue(v.getMobile());}else{row.createCell(0).setCellValue(v.getEmail());}row.createCell(1).setCellValue(BigDecimalUtil.outputConvert(v.getAmount()));row.createCell(2).setCellValue(v.getCounts());row.createCell(3).setCellValue(v.getGroups());i++;}ByteArrayOutputStream os = new ByteArrayOutputStream();try{try {wb.write(os);wb.close();} catch (IOException e) {e.printStackTrace();}byte[] content = os.toByteArray();InputStream is = new ByteArrayInputStream(content);response.reset();response.setContentType("application/vnd.ms-excel;charset=utf-8");response.setHeader("Content-Disposition", "attachment;filename="+ new String((fileName + ".xls").getBytes(), "iso-8859-1")); ServletOutputStream out = response.getOutputStream();BufferedInputStream bis = null;BufferedOutputStream bos = null;try {bis = new BufferedInputStream(is);bos = new BufferedOutputStream(out);byte[] buff = new byte[2048];int bytesRead;while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {bos.write(buff, 0, bytesRead);}} catch (final IOException e) {throw e;} finally {if (bis != null)bis.close();if (bos != null)bos.close();}}catch (Exception e){}return null;总结以上所述是⼩编给⼤家介绍的vue+springmvc导出excel数据的实现代码,希望对⼤家有所帮助,如果⼤家有任何疑问请给我留⾔,⼩编会及时回复⼤家的。