
把查询内容导出到excel表格
如何把数据库中查询到的数据导出到一个有组织的excel文件中?
解决方案
首先,引入必要的poi第三方库。
酷表ChatExcel
北大团队开发的通过聊天来操作Excel表格的AI工具
48 查看详情
立即学习“Java免费学习笔记(深入)”;
org.apache.poi poi 4.0.1 org.apache.poi poi-ooxml 4.0.1 org.apache.commons commons-compress 1.19 mysql mysql-connector-java 5.1.26 com.alibaba druid 1.0.9
然后,通过以下步骤将数据写入excel:
创建一个工作簿。创建一个表。为表创建行和单元格,并将数据插入单元格中。创建一个输出流,并将其写入磁盘。
以下是示例代码:
import org.apache.poi.xssf.usermodel.XSSFRow;import org.apache.poi.xssf.usermodel.XSSFSheet;import org.apache.poi.xssf.usermodel.XSSFWorkbook;import java.io.FileOutputStream;import java.io.IOException;public class WriteExcelTest { public static void main(String[] args) { XSSFWorkbook xssfWorkbook = new XSSFWorkbook(); XSSFSheet xssfSheet = xssfWorkbook.createSheet("first_sheet"); XSSFRow row1 = xssfSheet.createRow(0); XSSFRow row2 = xssfSheet.createRow(1); XSSFRow row3 = xssfSheet.createRow(2); XSSFRow row4 = xssfSheet.createRow(3); row1.createCell(0).setCellValue("姓名"); row1.createCell(1).setCellValue("年龄"); row1.createCell(2).setCellValue("性别"); row2.createCell(0).setCellValue("张三"); row2.createCell(1).setCellValue("18"); row2.createCell(2).setCellValue("男"); row3.createCell(0).setCellValue("李四"); row3.createCell(1).setCellValue("17"); row3.createCell(2).setCellValue("男"); row4.createCell(0).setCellValue("黄蓉"); row4.createCell(1).setCellValue("20"); row4.createCell(2).setCellValue("女"); FileOutputStream fileOutputStream = new FileOutputStream("D:/output.xlsx"); xssfWorkbook.write(fileOutputStream); try { if (fileOutputStream != null) { fileOutputStream.close(); } if (xssfWorkbook != null) { xssfWorkbook.close(); } } catch (IOException e) { e.printStackTrace(); } System.out.println("输出成功!"); }}
以上就是如何用Java将数据库查询结果导出到Excel表格?的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/377074.html
微信扫一扫
支付宝扫一扫