Java利用Apache POI将数据库数据导出为excel
将数据库中的数据导出为excel文件,供其他人查看
public class POITest {
public static void main(String[] args) {
POITest test = new POITest();
// test.readExcelToDB();
test.writeExcelFromDB();
}
static class Book{
public String title;
public String author;
public String date;
}
SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
ComboPooledDataSource dataSource;
public POITest() {
//初始化数据库连接池
try {
dataSource = new ComboPooledDataSource();
dataSource.setDriverClass("com.mysql.cj.jdbc.Driver");
dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/test?user=root&password=123456"
+ "&characterEncoding=utf8&serverTimezone=UTC");
} catch (PropertyVetoException e) {
e.printStackTrace();
}
}
//从数据库读取数据并保存为excel
public void writeExcelFromDB(){
List<Book> books = new ArrayList<POITest.Book>();
try {
Connection conn = dataSource.getConnection();
Statement statement = conn.createStatement();
ResultSet resultSet = statement.executeQuery("select * from book");
while(resultSet.next()){
Book book = new Book();
//第一列是id
book.title = resultSet.getString(2);
book.author = resultSet.getString(3);
book.date = format.format(resultSet.getDate(4));
books.add(book);
}
writeExcel(books);
} catch (SQLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
//HSSF 写excel
private void writeExcel(List<Book> books) throws IOException{
HSSFWorkbook workbook = new HSSFWorkbook();
//创建表
HSSFSheet sheet = workbook.createSheet("书本");
//创建首行
HSSFRow topRow = sheet.createRow(0);
//创建首行单元格样式
HSSFCellStyle topCellStyle = workbook.createCellStyle();
topCellStyle.setAlignment(HorizontalAlignment.CENTER);
topCellStyle.setFillForegroundColor(HSSFColor.YELLOW.index);
topCellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
topCellStyle.setBorderBottom(BorderStyle.THIN);
topCellStyle.setBorderLeft(BorderStyle.THIN);
topCellStyle.setBorderTop(BorderStyle.THIN);
topCellStyle.setBorderRight(BorderStyle.THIN);
HSSFFont topFont = workbook.createFont();
topFont.setColor(HSSFColor.BLACK.index);
topCellStyle.setFont(topFont);
HSSFCell topCell = topRow.createCell(0);
topCell.setCellValue("书名");
topCell.setCellStyle(topCellStyle);
topCell = topRow.createCell(1);
topCell.setCellValue("作者");
topCell.setCellStyle(topCellStyle);
topCell = topRow.createCell(2);
topCell.setCellValue("出版日期");
topCell.setCellStyle(topCellStyle);
//设置普通行单元格样式
HSSFCellStyle cellStyle = workbook.createCellStyle();
cellStyle.cloneStyleFrom(topCellStyle);
cellStyle.setFillForegroundColor(HSSFColor.WHITE.index);
cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
HSSFFont font = workbook.createFont();
font.setColor(HSSFColor.BLACK.index);
cellStyle.setFont(font);
for (int i=0; i<books.size(); i++) {
HSSFRow row = sheet.createRow(i+1);
Book book = books.get(i);
HSSFCell cell = row.createCell(0);
cell.setCellValue(book.title);
cell.setCellStyle(cellStyle);
cell = row.createCell(1);
cell.setCellValue(book.author);
cell.setCellStyle(cellStyle);
cell = row.createCell(2);
cell.setCellValue(book.date);
cell.setCellStyle(cellStyle);
}
FileOutputStream os = new FileOutputStream("d:/book.xls");
workbook.write(os);
os.flush();
os.close();
}
//从本地读取excel数据插入数据库
public void readExcelToDB(){
try {
List<Book> books = readExcel();
Connection conn = dataSource.getConnection();
String sql = "insert into book(title,author,submission_date) values(?,?,?)";
PreparedStatement preparedStatement = conn.prepareStatement(sql);
for (Book book : books) {
preparedStatement.setString(1, book.title);
preparedStatement.setString(2, book.author);
preparedStatement.setDate(3, new Date(format.parse(book.date).getTime()));
preparedStatement.addBatch();
}
preparedStatement.executeBatch();
} catch (SQLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
}
}
//HSSF 读excel
private List<Book> readExcel() throws IOException{
List<Book> books = new ArrayList<POITest.Book>();
InputStream is = new FileInputStream(new File("d:/book_2.xls"));
//得到工作薄
HSSFWorkbook workbook = new HSSFWorkbook(is);
//得到工作表
Sheet sheet = workbook.getSheetAt(0);
//得到行数
int rowNum = sheet.getLastRowNum();
//首行是标题行
for(int i=1; i<=rowNum; i++){
Book book = new Book();
Row row = sheet.getRow(i);
Cell cell = row.getCell(0);
book.title = cell.getStringCellValue();
cell = row.getCell(1);
book.author = cell.getStringCellValue();
cell = row.getCell(2);
book.date = format.format(cell.getDateCellValue());
books.add(book);
}
return books;
}
}
book建表语句
CREATE TABLE `book` (
`id` int(11) PRIMARY KEY NOT NULL AUTO_INCREMENT,
`title` varchar(100) DEFAULT NULL,
`author` varchar(40) DEFAULT NULL,
`submission_date` date DEFAULT NULL
)
设置列宽(index表示第几列,从0开始)
sheet.setColumnWidth(index, 30*256);
设置表格内容自动换行
CellStyle wrapStyle = workBook.createCellStyle();
wrapStyle.setWrapText(true); wrapCell.setCellStyle(wrapStyle);
wrapCell.setCellValue("第一行\r\n第二行");
Java利用Apache POI将数据库数据导出为excel的更多相关文章
- PCB MS SERVER 使用bcp命令将数据库数据导出到Excel
在前年工程系统与APS系统对接时,需将工程系统数据导出来给APS,采用的正是bcp命令实现,速度超快. 这里将此命令使用方法整理如下: 一.写SQL将表数据导出到Excel @echo "& ...
- Java利用Apache poi导出图表
jar compile('org.apache.poi:poi:4.0.1') compile('org.apache.poi:poi-scratchpad:4.0.1') compile('org. ...
- 使用apache的poi来实现数据导出到excel的功能——方式二
此次,介绍利用poi与layui table结合导出excel.这次不需要从数据库中查询出来的数据进行每一行的拼接那么麻烦,我们这次将标题定义一个id值,对应从数据库中查找出来的字段名即可. 1.po ...
- 使用apache的poi来实现数据导出到excel的功能——方式一
利用poi导出复杂样式的excel表格的实现. 我们要实现的效果是: 我们利用提前设计好模板样式,再在模板中填充数据的方式. 首先,pom.xml引入poi. <dependency> & ...
- Java:将数据库数据导出到Excel (一眼就看会)
所用Jar包 1. sqljdbc4.jar 连接数据库的Jar包(根据数据库的不同进行选择,我用的SqlServer2008) 2.Jxl.jar 访问Excel的Jar包 注意:支持以.xls结尾 ...
- Java中使用jxl.jar将数据导出为excel文件
Java对Excel文件的读写操作可由jxl.jar或poi.jar实现,这里使用jxl.jar完成对Excel文件的导出. 一.将Excel文件导出在本地 步骤: 创建文件 -> 创建 ...
- PHP将Excel导入数据库以及数据库数据导出至Excel
一.导入 导入需要使用能读取Excel的组件,网上也有比较好的组件,这里分享我使用的:下载 提取码:vxyn.(注意两个文件有引用关系) <?php //传入要导入的Excel的文件名 fun ...
- 利用 NUget包 EPPlus 实现数据导出到Excel(适用于MVC)
aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAvoAAABpCAIAAADEEBBGAAAJdElEQVR4nO3cy2ob5wLA8TxKnqTrrr
- 利用 NUget包 EPPlus 实现数据导出到Excel(适用于DTcms)
首先安装EPPlus 包
随机推荐
- 基于Unity·UGUI实现的RecycleList循环列表UI容器
在UI功能开发实践中,列表UI容器是我们经常使用一种UI容器组件.这种组件就根据输入的数据集合生成对应数据项目.从显示的方向来说,一般就分为水平排布和垂直排布的列表容器两种.列表容器为了在有限的界面空 ...
- vue下拉列表
最近在弄作品,做了个下拉列表.心想各位小哥哥.小姐姐可能会用到相同的需求,就把下拉列表封装一下,希望能对各位小哥哥,小姐姐有帮助 github地址:https://github.com/ClmPisc ...
- 原始的Ajax方法 (异步的 JavaScript 和 XML -- (Extensible Markup Language 可扩展标记语言))
<script language="javascript" type="text/javascript"> var request = false; ...
- VMware vCenter Server 6.5.0 U1
VMware vCenter Server 6.5.0 U1gName: VMware-VCSA-all-6.5.0-8024368.iso Release Date: 2018-03-20 Buil ...
- 阿里云API网关(3)快速入门(调用 API)
网关指南: https://help.aliyun.com/document_detail/29487.html?spm=5176.doc48835.6.550.23Oqbl 网关控制台: https ...
- scrapy-redis使用以及剖析
scrapy-redis是一个基于redis的scrapy组件,通过它可以快速实现简单分布式爬虫程序,该组件本质上提供了三大功能: scheduler - 调度器 dupefilter - URL去重 ...
- find文件查找
一.locate locate基于数据库索引来查找文件,数据库在开机时一段时间对更新,不会实时更新,数据库存放在(/var/lib/mlocate/mlocate.db),可以用updatedb来手动 ...
- pandas笔记
axis = 1表示按列的方向遍历 axis = 0表示按行的方向遍历 Usually axis=0 is said to be "column-wise" (and axis=1 ...
- SublimeText用FileHeader给代码文件生成头部注释
https://github.com/shiyanhui/FileHeader 修改的模板在这个路径下:C:\Users\[USERNAME]\AppData\Roaming\Sublime Text ...
- 一种dubbo逻辑路由方案(服务化隔离环境)
背景介绍 现在很多的公司都在用dubbo.springcloud做为服务化/微服务的开发框架,服务化之后应用越来越多,链路越来越长,服务环境的治理变的很困难.比如:研发团队的人很多的,同时有几个分支在 ...