/** 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
*/
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;
}