将数据库中的数据导出为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. OptaPlanner - 把example运行起来(运行并浅析Cloud balancing)

    经过上面篇长篇大论的理论之后,在开始讲解Optaplanner相关基本概念及用法之前,我们先把他们提供的示例运行起来,好先让大家看看它是如何工作的.OptaPlanner的优点不仅仅是提供详细丰富的文 ...

  2. 使用Google 的 gson方式解析json

    gson支持解析的类型还是比较全面的,包括JavaBean,List<JavaBean>,List<String>,Map等,使用起来也是比较方便,下面根据代码示例给出总结: ...

  3. 记一次SQL调优/优化(SQL tuning)——性能大幅提升千倍以上

    好久不写东西了,一直忙于各种杂事儿,恰巧昨天有个用户研发问到我一个SQL调优的问题,说性能太差,希望我能给调优下,最近有些懒,可能和最近太忙有关系,本来打算问问现在的情况,如果差不多就不调了,那哥们儿 ...

  4. 09-TypeScript中的继承

    在后端开发语言中,继承是非常重要的概念,继承可以让子类具有父类的成员和方法,通过实例化子类,就可以访问父类的成员和方法. 在JavaScript中,需要通过原型模式来模拟继承的实现.而在TypeScr ...

  5. python小练习之一

    下面的练习本身不难,比如打印1到10,计算1+2+3+...+100 ,最后一个是计算 1-2+3-4...-100 用了类的方法实现 用了列表生成器 用"高级"一丢丢的写法来实现 ...

  6. angluarjs2入门学习资源

    http://www.runoob.com/angularjs2/angularjs2-tutorial.htmlhttps://segmentfault.com/a/1190000008423981 ...

  7. Java课后练习

    1.利用循环输出:************************* public class Shape { public static void main(String[] args) { for ...

  8. String、StringBuffer、StringBulider之间的联系和区别

    首先,我们大概总体的解释一下这三者的区别和联系 String的值是不可变的,这就导致每次对String的操作都会生成新的String对象,不仅效率低下,而且大量浪费有限的内存空间. StringBuf ...

  9. bs4解析要获取被注掉的部分需先将注释符号去掉

    <div class="xzcf-content"> <div id="sfxz"> <div class="main- ...

  10. 用js来实现那些数据结构06(队列)

    其实队列跟栈有很多相似的地方,包括其中的一些方法和使用方式,只是队列使用了与栈完全不同的原则,栈是后进先出原则,而队列是先进先出(First In First Out). 一.队列    队列是一种特 ...