dinux 2014-05-06
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.collections.CollectionUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import oss.util.debug.LogHome;
/**
* Title: 导出excel<br>
* Description: <br>
*
*/
public class ExportExcelUtils {
private JdbcTemplate jdbcTemplate;
public JdbcTemplate getJdbcTemplate() {
return jdbcTemplate;
}
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public void export(List columnTitleList, final List columnNameList, String sql, List args, HttpServletResponse response) throws Exception
{
try
{
if (CollectionUtils.isEmpty(columnTitleList) || CollectionUtils.isEmpty(columnNameList) || columnTitleList.size() != columnNameList.size()) {
throw new Exception("列标题数量 和列数量 不一致");
}
HSSFWorkbook book = new HSSFWorkbook();
final HSSFSheet sheet = book.createSheet();
HSSFRow row = sheet.createRow(0);
for (int i = 0; i < columnTitleList.size(); i++) {
HSSFCell cell = row.createCell((short)i);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
cell.setCellValue(columnTitleList.get(i).toString());
}
this.jdbcTemplate.query(sql, args.toArray(), new RowMapper() {
public Object mapRow(ResultSet rs, int nRow) throws SQLException {
if (nRow%5000 == 0 && nRow != 0) {
LogHome.getLog().info("已处理" + nRow + "条");
}
HSSFRow row = sheet.createRow(nRow+1);
for (int i = 0; i < columnNameList.size(); i++) {
String colValue = rs.getString(columnNameList.get(i).toString());
HSSFCell cell = row.createCell((short)i);
cell.setEncoding(HSSFCell.ENCODING_UTF_16);
cell.setCellValue(colValue);
}
return null;
}}) ;
LogHome.getLog().info("输出excel文件");
response.setContentType("application/vnd.ms-excel");
book.write(response.getOutputStream());
}
catch (Exception e)
{
LogHome.logExceptionStackTrace(e);
throw e;
}
}
}