欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Java POI 数据导出到Excel 2010

程序员文章站 2024-02-24 12:58:04
...
package com.demo.utils;
import java.io.FileOutputStream;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFCell;

public class SimpleExportToExcel {

public static void main(String[] args) {

try{
//创建新的Excel工作薄
SXSSFWorkbook workbook=new SXSSFWorkbook ();
//如果新建一个名为“sheet1”的工作表
Sheet sheet=workbook.createSheet("sheet1");
// Sheet sheet=workbook.createSheet();
//在索引0的位置创建行(最顶端的行)
Row row=sheet.createRow(0);
//在索引0的位置创建单元格(左上端)
Cell cell=row.createCell(0);
//定义单元格为字符串类型
cell.setCellType(XSSFCell.CELL_TYPE_STRING);
//在单元格中输入一些内容
cell.setCellValue("新插入值");
//新建文件输出流
FileOutputStream fOut=new FileOutputStream("d:\\bookdata.xlsx");
//将数据写入Excel
workbook.write(fOut);
fOut.flush();
fOut.close();
}catch(Exception e){
e.printStackTrace();
}
}

}

package com.demo.utils;
import java.io.FileOutputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.List;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.streaming.SXSSFCell;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFCell;

import com.demo.dao.impl.BookDaoImpl;
import com.demo.entity.TBook;

public class ExportBookDataToExcel {

public static void main(String[] args) {

try{
//创建新的Excel工作薄
SXSSFWorkbook workbook=new SXSSFWorkbook ();

//如果新建一个名为“sheet1”的工作表
Sheet sheet=workbook.createSheet("bookSheet");
sheet.setColumnWidth(0, 2560);
sheet.setColumnWidth(1, 5560);
sheet.setColumnWidth(2, 5560);
sheet.setColumnWidth(3, 5560);
sheet.setColumnWidth(4, 2560);

Row row=null;
Cell cell=null;

Connection connection = DBUtils.getConnection();
String sql = "SELECT ID,NAME,AUTHER,PRESS,PRICE FROM T_BOOK";
PreparedStatement ps = connection.prepareStatement(sql);
ResultSet rs = ps.executeQuery();

int index=0;
while (rs.next()) {
row=sheet.createRow(index);index++;

cell=row.createCell(0);
cell.setCellType(SXSSFCell.CELL_TYPE_NUMERIC);
cell.setCellValue(rs.getInt(1));

cell=row.createCell(1);
cell.setCellType(SXSSFCell.CELL_TYPE_STRING);
cell.setCellValue(rs.getString(2));

cell=row.createCell(2);
cell.setCellType(SXSSFCell.CELL_TYPE_STRING);
cell.setCellValue(rs.getString(3));

cell=row.createCell(3);
cell.setCellType(SXSSFCell.CELL_TYPE_STRING);
cell.setCellValue(rs.getString(4));

cell=row.createCell(4);
cell.setCellType(SXSSFCell.CELL_TYPE_NUMERIC);
cell.setCellValue(rs.getDouble(5));

}

//新建文件输出流
FileOutputStream fOut=new FileOutputStream("d:\\bookdata.xlsx");
//将数据写入Excel
workbook.write(fOut);
fOut.flush();
fOut.close();

}catch(Exception e){
e.printStackTrace();
}finally {
DBUtils.closeConnection();
}
}
}