将数据库中的数据导出为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的更多相关文章

  1. PCB MS SERVER 使用bcp命令将数据库数据导出到Excel

    在前年工程系统与APS系统对接时,需将工程系统数据导出来给APS,采用的正是bcp命令实现,速度超快. 这里将此命令使用方法整理如下: 一.写SQL将表数据导出到Excel @echo "& ...

  2. Java利用Apache poi导出图表

    jar compile('org.apache.poi:poi:4.0.1') compile('org.apache.poi:poi-scratchpad:4.0.1') compile('org. ...

  3. 使用apache的poi来实现数据导出到excel的功能——方式二

    此次,介绍利用poi与layui table结合导出excel.这次不需要从数据库中查询出来的数据进行每一行的拼接那么麻烦,我们这次将标题定义一个id值,对应从数据库中查找出来的字段名即可. 1.po ...

  4. 使用apache的poi来实现数据导出到excel的功能——方式一

    利用poi导出复杂样式的excel表格的实现. 我们要实现的效果是: 我们利用提前设计好模板样式,再在模板中填充数据的方式. 首先,pom.xml引入poi. <dependency> & ...

  5. Java:将数据库数据导出到Excel (一眼就看会)

    所用Jar包 1. sqljdbc4.jar 连接数据库的Jar包(根据数据库的不同进行选择,我用的SqlServer2008) 2.Jxl.jar 访问Excel的Jar包 注意:支持以.xls结尾 ...

  6. Java中使用jxl.jar将数据导出为excel文件

      Java对Excel文件的读写操作可由jxl.jar或poi.jar实现,这里使用jxl.jar完成对Excel文件的导出. 一.将Excel文件导出在本地 步骤:   创建文件 -> 创建 ...

  7. PHP将Excel导入数据库以及数据库数据导出至Excel

    一.导入 导入需要使用能读取Excel的组件,网上也有比较好的组件,这里分享我使用的:下载  提取码:vxyn.(注意两个文件有引用关系) <?php //传入要导入的Excel的文件名 fun ...

  8. 利用 NUget包 EPPlus 实现数据导出到Excel(适用于MVC)

    aaarticlea/png;base64,iVBORw0KGgoAAAANSUhEUgAAAvoAAABpCAIAAADEEBBGAAAJdElEQVR4nO3cy2ob5wLA8TxKnqTrrr

  9. 利用 NUget包 EPPlus 实现数据导出到Excel(适用于DTcms)

    首先安装EPPlus 包

随机推荐

  1. 03-移动端开发教程-CSS3新特性(下)

    1. CSS3动画 1.1 过渡的缺点 transition的优点在于简单易用,但是它有几个很大的局限. transition需要事件触发,所以没法在网页加载时自动发生. transition是一次性 ...

  2. 07-TypeScript的For循环

    在传统的JavaScript中,关于循环,可以有两种方式,一种是forEach,一种是for. forEach的用法如下: var sarr=[1,2,3,4]; sarr.desc="he ...

  3. [扩展推荐] —— Laravel Log 增强

    Laravel Log Enhancer 是 Laravel 5.6  的一个扩展包,可以在 Laravel 日志中添加额外的数据. 得益于 Laravel 5.6 中日志的更新,这个包利用这些特性扩 ...

  4. maven入门(8)maven的依赖管理

    我们项目中用到的jar包可以通过依赖的方式引入,构建项目的时候从Maven仓库下载即可. 1. 依赖配置    依赖可以声明如下: <project> ... <dependenci ...

  5. apigw鉴权分析(1-3)百度 AI - 鉴权方式分析

    http://ai.baidu.com/docs#/Begin/top 一.访问入口 二.鉴权方式分析 1.鉴权认证方式一 - access_token - 针对HTTP API调用者 2.鉴权认证方 ...

  6. POJ1015 && UVA - 323 ~Jury Compromise(dp路径)

    In Frobnia, a far-away country, the verdicts in court trials are determined by a jury consisting of ...

  7. leetcode算法:Reshape the Matrix

    In MATLAB, there is a very useful function called 'reshape', which can reshape a matrix into a new o ...

  8. 基于UDP协议的控制台聊天程序(c++版)

    本博客由Rcchio原创,转载请告知作者 ------------------------------------------------------------------------------- ...

  9. 数据库“行专列”操作---使用row_number()over(partition by 分组字段 [order by 排序字段])

    测试样例: create table test(rsrp string,rsrq string,tkey string,distan string); '); '); '); '); select * ...

  10. 如何用elementui去实现图片上传和表单提交,用axios的post方法

    下面是在vue搭建的脚手架项目中的组件component文件夹下面的upload.vue文件中的内容 <!--这个组件主要用来研究upload这个elementui的上传插件组件--> & ...