
把查询内容导出到excel表格
如何把数据库中查询到的数据导出到一个有组织的excel文件中?
解决方案
首先,引入必要的poi第三方库。
立即学习“Java免费学习笔记(深入)”;
<!-- 使用apache poi需要的依赖 --> <dependency> <groupid>org.apache.poi</groupid> <artifactid>poi</artifactid> <version>4.0.1</version> </dependency> <dependency> <groupid>org.apache.poi</groupid> <artifactid>poi-ooxml</artifactid> <version>4.0.1</version> </dependency> <dependency> <groupid>org.apache.commons</groupid> <artifactid>commons-compress</artifactid> <version>1.19</version> </dependency> <!-- 使用druid连接池建立java程序与mysql数据库的连接需要的依赖 --> <dependency> <groupid>mysql</groupid> <artifactid>mysql-connector-java</artifactid> <version>5.1.26</version> </dependency> <dependency> <groupid>com.alibaba</groupid> <artifactid>druid</artifactid> <version>1.0.9</version> </dependency>
然后,通过以下步骤将数据写入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表格?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号