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();
}
}
}
分享到:
2013-10-17 11:01
浏览 10719
评论
1 楼
贝塔ZQ
2016-12-28
导出数据到excel文档中,可以使用pageoffice插件实现,可以支持03,07,10,13,16版本的office文件。