用prepareStatement、resultSet写的excel实例分析
2013-03-14 17:10
155 查看
/** Map<String, Object> map=writeToExl( sql,path, filename, originalPath);
file=(File) map.get("file");
* 生成EXCLE 文件
*
* @param sql
* 数据查询sql
* @param path
* 文件生成路径
* @param filename
* 文件名
* @param originalPath
* 原始excle模版路径
* @return
*/
@SuppressWarnings("deprecation")
public Map<String, Object> writeToExl( String sql,
String path, String filename, String originalPath) {
if (StringUtils.isBlank(path)) {
path = SettingService.tempFilePath();//SettingService类的tempFilePath()方法主要是用来获取生成excel存档的文件夹
File f = new File(path);
//如果没有该文件夹,则重新生成
if (!f.exists()) {
f.mkdirs();
}
}
//excel文件名如果没有指定的,则随机生成一个为文件名
if (StringUtils.isBlank(filename)) {
filename = UUID.randomUUID().toString();
}
PreparedStatement st = null;//PreparedStatement 可以达到预处理
ResultSet rs = null;/*结果集(ResultSet)是数据中查询结果返回的一种对象,可以说结果集是一个存储查询结果的对象,但是结果集并不仅仅具有存储的功能,他同时还具有操纵数据的功能,可能完成对数据的更新等.*/
File file = null;
Map<String, Object> returnMap = new HashMap<String, Object>();
try {
// 总记录数
Long count = null;
String countSql = "SELECT COUNT(*) FROM ("
+ sql+")";
if (!StringUtils.isBlank(countSql)) {
count = Utils.converToLong(getSession()
.createSQLQuery(countSql).uniqueResult());//求数据数目
} else {
count = 1000L;
}
// returnMap.put("count", count);
// 执行 PrepareStatement
st = ((SessionImpl) getSession()).getBatcher()
.prepareStatement(sql);
rs = st.executeQuery();
// 头行汉字
ResultSetMetaData metadata = rs.getMetaData();
int columnCount = metadata.getColumnCount();
List<Integer> columns = new ArrayList<Integer>(columnCount);
List<String> columnNames = new ArrayList<String>(columnCount);
int col = 0;
//数据列
for (int i = 0; i < columnCount; i++) {
// nextLine[i] = metadata.getColumnName(i + 1);
String n = metadata.getColumnName(i + 1);
String cn = n;
if (!StringUtils.isBlank(cn)) {
columns.add(i);
columnNames.add(cn);
// nmap.put(cn, i);
}
}
HSSFWorkbook wb=null;
FileOutputStream fileOut=null;
String tmpFileDir = null;
boolean merge = false;
// 计算是否需要拆分成几个文件
if (count >= Report.MAX_SHEET_NUMBER) {
merge = true;
tmpFileDir = FilenameUtils.normalize(path + "/"
+ UUID.randomUUID().toString());
new File(tmpFileDir).mkdirs();
file = new File(FilenameUtils.normalize(path + "/"
+ StringUtils.substringBefore(filename, ".") + ".zip"));
returnMap.put("suffix", "zip");
} else {
file = new File(FilenameUtils.normalize(path + "/"
+ StringUtils.substringBefore(filename, ".") + ".xls"));
returnMap.put("suffix", "xls");
}
returnMap.put("file", file);
int pageIndex = 1;
int rowIndex = 2;
HSSFSheet sheet=null;
HSSFRow row =null;
POIFSFileSystem fs=null;
boolean isBlank = true;
boolean writeFlag = false;
wb = new HSSFWorkbook();
FileUtils.copyFile(
new File(FilenameUtils.normalize(SimpleFileUtils
.getRootPath()+ originalPath)),file, true);
fs = new POIFSFileSystem(new FileInputStream(file.getPath()));
wb = new HSSFWorkbook(fs);
while (rs.next()) {
if (rowIndex == 2) {
File _file = file;
// fileWriter = new OutputStreamWriter(new FileOutputStream(
// _file), "GBK");
if (merge) {
isBlank = false;
_file = new File(tmpFileDir + "/" + pageIndex + ".xls");
}
FileUtils.copyFile(
new File(FilenameUtils.normalize(SimpleFileUtils
.getRootPath()+ originalPath)),_file, true);//复制模版到目标excel
fs = new POIFSFileSystem(new FileInputStream(_file.getPath()));
wb = new HSSFWorkbook(fs);
while (wb.getSheetAt(0).getRow(1).getCell(col) != null) {
columns.add(col);
col++;
}
}
row = wb.getSheetAt(0).createRow(rowIndex);
// String[] nextLine = new String[columns.size()];
int j = 0;
for (int i = 0; i < columnCount; i++) {
if (columns.contains(i)) {
HSSFCell cell = row.createCell(j++);
String value = HibernateHelper.getColumnStrValue(rs,
metadata.getColumnType(i + 1), i + 1);
cell.setCellValue(value);
}
}
rowIndex = rowIndex + 1;
if (rowIndex >= Report.MAX_SHEET_NUMBER) {
fileOut = new FileOutputStream(tmpFileDir + "/" + pageIndex + ".xls");
wb.write(fileOut);
fileOut.close();
rowIndex = 2;
pageIndex = pageIndex + 1;
writeFlag = true;
}
}
if(writeFlag) {
fileOut = new FileOutputStream(tmpFileDir + "/" + pageIndex + ".xls");
wb.write(fileOut);
fileOut.close();
}
if (isBlank) {
fileOut = new FileOutputStream(file.getPath());
wb.write(fileOut);
fileOut.close();
}
// 合并文件
if (merge) {
Attachment.compressed(tmpFileDir, file);
// 删除临时目录
FileUtils.deleteDirectory(new File(tmpFileDir));
}
} catch (IOException e) {
e.printStackTrace();
throw new BusinessException(e.toString());
} catch (HibernateException e) {
e.printStackTrace();
throw new BusinessException(e.toString());
} catch (SQLException e) {
e.printStackTrace();
throw new BusinessException(e.toString());
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (st != null) {
try {
st.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return returnMap;
}
file=(File) map.get("file");
* 生成EXCLE 文件
*
* @param sql
* 数据查询sql
* @param path
* 文件生成路径
* @param filename
* 文件名
* @param originalPath
* 原始excle模版路径
* @return
*/
@SuppressWarnings("deprecation")
public Map<String, Object> writeToExl( String sql,
String path, String filename, String originalPath) {
if (StringUtils.isBlank(path)) {
path = SettingService.tempFilePath();//SettingService类的tempFilePath()方法主要是用来获取生成excel存档的文件夹
File f = new File(path);
//如果没有该文件夹,则重新生成
if (!f.exists()) {
f.mkdirs();
}
}
//excel文件名如果没有指定的,则随机生成一个为文件名
if (StringUtils.isBlank(filename)) {
filename = UUID.randomUUID().toString();
}
PreparedStatement st = null;//PreparedStatement 可以达到预处理
ResultSet rs = null;/*结果集(ResultSet)是数据中查询结果返回的一种对象,可以说结果集是一个存储查询结果的对象,但是结果集并不仅仅具有存储的功能,他同时还具有操纵数据的功能,可能完成对数据的更新等.*/
File file = null;
Map<String, Object> returnMap = new HashMap<String, Object>();
try {
// 总记录数
Long count = null;
String countSql = "SELECT COUNT(*) FROM ("
+ sql+")";
if (!StringUtils.isBlank(countSql)) {
count = Utils.converToLong(getSession()
.createSQLQuery(countSql).uniqueResult());//求数据数目
} else {
count = 1000L;
}
// returnMap.put("count", count);
// 执行 PrepareStatement
st = ((SessionImpl) getSession()).getBatcher()
.prepareStatement(sql);
rs = st.executeQuery();
// 头行汉字
ResultSetMetaData metadata = rs.getMetaData();
int columnCount = metadata.getColumnCount();
List<Integer> columns = new ArrayList<Integer>(columnCount);
List<String> columnNames = new ArrayList<String>(columnCount);
int col = 0;
//数据列
for (int i = 0; i < columnCount; i++) {
// nextLine[i] = metadata.getColumnName(i + 1);
String n = metadata.getColumnName(i + 1);
String cn = n;
if (!StringUtils.isBlank(cn)) {
columns.add(i);
columnNames.add(cn);
// nmap.put(cn, i);
}
}
HSSFWorkbook wb=null;
FileOutputStream fileOut=null;
String tmpFileDir = null;
boolean merge = false;
// 计算是否需要拆分成几个文件
if (count >= Report.MAX_SHEET_NUMBER) {
merge = true;
tmpFileDir = FilenameUtils.normalize(path + "/"
+ UUID.randomUUID().toString());
new File(tmpFileDir).mkdirs();
file = new File(FilenameUtils.normalize(path + "/"
+ StringUtils.substringBefore(filename, ".") + ".zip"));
returnMap.put("suffix", "zip");
} else {
file = new File(FilenameUtils.normalize(path + "/"
+ StringUtils.substringBefore(filename, ".") + ".xls"));
returnMap.put("suffix", "xls");
}
returnMap.put("file", file);
int pageIndex = 1;
int rowIndex = 2;
HSSFSheet sheet=null;
HSSFRow row =null;
POIFSFileSystem fs=null;
boolean isBlank = true;
boolean writeFlag = false;
wb = new HSSFWorkbook();
FileUtils.copyFile(
new File(FilenameUtils.normalize(SimpleFileUtils
.getRootPath()+ originalPath)),file, true);
fs = new POIFSFileSystem(new FileInputStream(file.getPath()));
wb = new HSSFWorkbook(fs);
while (rs.next()) {
if (rowIndex == 2) {
File _file = file;
// fileWriter = new OutputStreamWriter(new FileOutputStream(
// _file), "GBK");
if (merge) {
isBlank = false;
_file = new File(tmpFileDir + "/" + pageIndex + ".xls");
}
FileUtils.copyFile(
new File(FilenameUtils.normalize(SimpleFileUtils
.getRootPath()+ originalPath)),_file, true);//复制模版到目标excel
fs = new POIFSFileSystem(new FileInputStream(_file.getPath()));
wb = new HSSFWorkbook(fs);
while (wb.getSheetAt(0).getRow(1).getCell(col) != null) {
columns.add(col);
col++;
}
}
row = wb.getSheetAt(0).createRow(rowIndex);
// String[] nextLine = new String[columns.size()];
int j = 0;
for (int i = 0; i < columnCount; i++) {
if (columns.contains(i)) {
HSSFCell cell = row.createCell(j++);
String value = HibernateHelper.getColumnStrValue(rs,
metadata.getColumnType(i + 1), i + 1);
cell.setCellValue(value);
}
}
rowIndex = rowIndex + 1;
if (rowIndex >= Report.MAX_SHEET_NUMBER) {
fileOut = new FileOutputStream(tmpFileDir + "/" + pageIndex + ".xls");
wb.write(fileOut);
fileOut.close();
rowIndex = 2;
pageIndex = pageIndex + 1;
writeFlag = true;
}
}
if(writeFlag) {
fileOut = new FileOutputStream(tmpFileDir + "/" + pageIndex + ".xls");
wb.write(fileOut);
fileOut.close();
}
if (isBlank) {
fileOut = new FileOutputStream(file.getPath());
wb.write(fileOut);
fileOut.close();
}
// 合并文件
if (merge) {
Attachment.compressed(tmpFileDir, file);
// 删除临时目录
FileUtils.deleteDirectory(new File(tmpFileDir));
}
} catch (IOException e) {
e.printStackTrace();
throw new BusinessException(e.toString());
} catch (HibernateException e) {
e.printStackTrace();
throw new BusinessException(e.toString());
} catch (SQLException e) {
e.printStackTrace();
throw new BusinessException(e.toString());
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (st != null) {
try {
st.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return returnMap;
}
相关文章推荐
- Excel数据分析实例——各省人口数量及增长
- Python读取Excel的方法实例分析
- 使用PHPExcel操作Excel用法实例分析
- 使用PHPExcel操作Excel用法实例分析_PHP教程
- c#读取excel方法实例分析
- 实例分析EXCEL中的IF嵌套和VLOOKUP
- Excel数据分析与业务建模_第二章_查找函数VLOOKUP及HLOOKUP(语法及应用实例)
- 使用PHPExcel操作Excel用法实例分析
- Python读取Excel的方法实例分析
- Excel数据分析与业务建模_第三章_引用函数INDEX(语法详解及应用实例)
- Excel数据分析与业务建模_第四章_匹配函数MATCH(语法详解及应用实例)
- java中object类实例分析
- C#分布式事务的超时处理实例分析
- Mediastream2 用法介绍及简明实例分析
- 杨建:网站加速--实例分析篇
- javascript面向对象之定义成员方法实例分析
- Android控件之AnalogClock与DigitalClock用法实例分析
- 利用excel分析IIS服务器日志
- Linux网络编程——原始套接字实例:MAC 头部报文分析
- Purchase购物车实例分析