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 包
随机推荐
- Fluent Interface(流式接口)
我最初接触这个概念是读自<<模式-工程化实现及扩展>>,另外有Martin fowler大师 所写http://martinfowler.com/bliki/FluentInt ...
- vue class与style 绑定详解——小白速会
一.绑定class的几种方式 1.对象语法 直接看例子: <div id="app3"> <div :class="{'success':isSucce ...
- nyoj 第几是谁
第几是谁? 时间限制:3000 ms | 内存限制:65535 KB 难度:3 描述 现在有"abcdefghijkl"12个字符,将其按字典序排列,如果给出任意一种排列, ...
- js进度条小事例
<style> #div1{width: 500px;height: 20px;border: 1px solid gray;} #div2{height: 20px;width: 0px ...
- SpringMvc返回报文形式的控制-验证方法: JSON or HTML or XML
首先,请求通过accept请求头声明了支持的返回格式 然后,框架根据该请求头和代码实现(注解)选择了对应的MessageConverter处理返回! 一.验证过程 1.返回html 1.1.请求组装 ...
- mongodb聚合的使用
聚合: 主要用于计算和统计等,类似sql种的sum() avg() db.集合.aggregate( { 管道:{表达式} } ) 常用的管道: $group:将集合中的文档按照字段进行分组 $mat ...
- jsp 九大内置对象和其作用详解
JSP中一共预先定义了9个这样的对象,分别为:request.response.session.application.out.pagecontext.config.page.exception 1. ...
- Spring整合MyBaytis
1.准备jar包 A.第一种方式:配置SqlSessionFactoryBean+配置SqlSessionTemplate a.项目结构 b.applicationContext.xml 带详细注释 ...
- JavaScript作用域那些事
作用域 (1).作用域也叫执行环境(execution context)是JavaScript中一个重要的概念.执行环境定义了变量或函数有权访问的其他数据,决定了它们各自的行为.在JavaScript ...
- 【vuejs深入一】深入学习vue指令,自定义指令解决开发痛点
写在前面 一个好的架构需要经过血与火的历练,一个好的工程师需要经过无数项目的摧残. 最近博主我沉淀了几个月,或者说懒了几个月.然而大佬的指点总是一针见血,能够让人看到方向.所以我现在有觉得,一个好的 ...