本篇文章给大家带来的内容是关于如何使用SpringMVC生成一个Excel文件?有一定的参考价值,有需要的朋友可以参考一下,希望对你有所帮助。
通过Java来生成Excel文件或者导入一个Excel文件的数据都需要用到Apache的一个POI包,这里我就先把这个包提供出来。
<dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.9</version> </dependency>
这里我用的SpringBoot创建的项目,创建过程就不做累述了,直接操刀,开始把数据库的数据导成一个Excel文件
正式开始写这个Demo
1.创建一个ExcelUtil类,这个类就是对Excel进行操作,主要两个方法。
1-1.exportFile():把数据导出成一个Excel文件;
1-2.importFile():把指定文件的数据导入进来;
users表结构如下:
id | username | password | +----+-----------+-----------+ | 1 | yx12156ok | yx27787ok | | 2 | yangxiang | 123456 | | 3 | zhangsan | 666666 | | 4 | wangwu | 999999 | | 5 | xiaoming | xiaoming这里先贴出ExcelUtil类导入的实现,下面再做详细解释:
public class ExcelUtil { private final String excel2003 = "xls"; private final String excel2007 = "xlsx"; private Workbook workbook; private Sheet sheet; private Row row; private Cell cell; private CellStyle style; private File file; //初始化表结构和生成表头 public ExcelUtil(String[] titles,File file) { this.file = file; String fileName = this.file.getName(); this.workbook = getWorkbook(fileName); if(workbook == null) return; this.sheet = this.workbook.createSheet(); this.row = this.sheet.createRow(0); this.style = this.workbook.createCellStyle(); this.style.setAlignment(CellStyle.ALIGN_CENTER); for(int i = 0 ; i < titles.length ; i ++) { cell = row.createCell(i); //创建列 cell.setCellValue(titles[i]); //赋值 cell.setCellStyle(style); //样式 } } public void genertedExportUsersFile(List<Users> data) throws IOException { //遍历每一行数据 for(int i = 0; i < data.size() ; i ++) { int j = 0; Users user = data.get(i); row = sheet.createRow(i+1); row.setRowStyle(style); row.createCell(j++).setCellValue(Optional.of(user.getId()).orElse(null)); row.createCell(j++).setCellValue(Optional.of(user.getUsername()).orElse(null)); row.createCell(j++).setCellValue(Optional.of(user.getPassword()).orElse(null)); } } public void genertedExportStudentFile(List<Student> data) { //遍历每一行数据 for(int i = 0,j = 0 ; i < data.size() ; i ++) { Student student = data.get(i); row = sheet.createRow(i+1); row.setRowStyle(style); row.createCell(j++).setCellValue(Optional.of(student.getId()).orElse(null)); row.createCell(j++).setCellValue(Optional.of(student.getUsername()).orElse(null)); row.createCell(j++).setCellValue(Optional.of(student.getPassword()).orElse(null)); row.createCell(j++).setCellValue(Optional.of(student.getStuname()).orElse(null)); row.createCell(j++).setCellValue(Optional.of(student.getStusex()).orElse(null)); } } public void write() throws IOException { //把数据写入表格文件 OutputStream out = new FileOutputStream(this.file); this.workbook.write(out); out.close(); } private Workbook getWorkbook(String fileName) { //根据文件后缀名来获取Excel文件是2003版的还是2007版的 String type = checkFileType(fileName); //根据版本的不同实例不同的对象 if(type.equals(this.excel2003)) return new HSSFWorkbook(); else if(type.equals(this.excel2007)) return new XSSFWorkbook(); return null; } private String checkFileType(String fileName) { return fileName.substring(fileName.lastIndexOf(".")+1); } }
现在我就来讲一讲几个方法的作用:
Constructor方法:对表结构对象进行初始化以及生产表头;
genertedExportUsersFile方法:生成表的数据,此时数据应该还未真正写入;
write方法:把生成的表写入传入的File类里,也就是创建的文件;
getWorkbook方法:获取2003版本的或者2007版本的Excel对象;
checkFileType方法:获取文件的后缀名。
以上是如何使用SpringMVC生成一个Excel文件?的详细内容。更多信息请关注PHP中文网其他相关文章!

JVM'SperformanceIsCompetitiveWithOtherRuntimes,operingabalanceOfspeed,安全性和生产性。1)JVMUSESJITCOMPILATIONFORDYNAMICOPTIMIZAIZATIONS.2)c提供NativePernativePerformanceButlanceButlactsjvm'ssafetyFeatures.3)

JavaachievesPlatFormIndependencEthroughTheJavavIrtualMachine(JVM),允许CodeTorunonAnyPlatFormWithAjvm.1)codeisscompiledIntobytecode,notmachine-specificodificcode.2)bytecodeisisteredbytheybytheybytheybythejvm,enablingcross-platerssectectectectectross-eenablingcrossectectectectectection.2)

TheJVMisanabstractcomputingmachinecrucialforrunningJavaprogramsduetoitsplatform-independentarchitecture.Itincludes:1)ClassLoaderforloadingclasses,2)RuntimeDataAreafordatastorage,3)ExecutionEnginewithInterpreter,JITCompiler,andGarbageCollectorforbytec

JVMhasacloserelationshipwiththeOSasittranslatesJavabytecodeintomachine-specificinstructions,managesmemory,andhandlesgarbagecollection.ThisrelationshipallowsJavatorunonvariousOSenvironments,butitalsopresentschallengeslikedifferentJVMbehaviorsandOS-spe

Java实现“一次编写,到处运行”通过编译成字节码并在Java虚拟机(JVM)上运行。1)编写Java代码并编译成字节码。2)字节码在任何安装了JVM的平台上运行。3)使用Java原生接口(JNI)处理平台特定功能。尽管存在挑战,如JVM一致性和平台特定库的使用,但WORA大大提高了开发效率和部署灵活性。

JavaachievesPlatFormIndependencethroughTheJavavIrtualMachine(JVM),允许Codetorunondifferentoperatingsystemsswithoutmodification.thejvmcompilesjavacodeintoplatform-interploplatform-interpectentbybyteentbytybyteentbybytecode,whatittheninternterninterpretsandectectececutesoneonthepecificos,atrafficteyos,Afferctinginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginginging

JavaispoperfulduetoitsplatFormitiondence,对象与偏见,RichstandardLibrary,PerformanceCapabilities和StrongsecurityFeatures.1)Platform-dimplighandependectionceallowsenceallowsenceallowsenceallowsencationSapplicationStornanyDevicesupportingJava.2)

Java的顶级功能包括:1)面向对象编程,支持多态性,提升代码的灵活性和可维护性;2)异常处理机制,通过try-catch-finally块提高代码的鲁棒性;3)垃圾回收,简化内存管理;4)泛型,增强类型安全性;5)ambda表达式和函数式编程,使代码更简洁和表达性强;6)丰富的标准库,提供优化过的数据结构和算法。


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

适用于 Eclipse 的 SAP NetWeaver 服务器适配器
将Eclipse与SAP NetWeaver应用服务器集成。

SublimeText3 英文版
推荐:为Win版本,支持代码提示!

SecLists
SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

安全考试浏览器
Safe Exam Browser是一个安全的浏览器环境,用于安全地进行在线考试。该软件将任何计算机变成一个安全的工作站。它控制对任何实用工具的访问,并防止学生使用未经授权的资源。