Excel導出數據服務器
下面是個demo,Java實現生成Excel文件 打包成zip,提供下載!
app
@Controller
@RequestMapping("/importOut/")
public class ImportOutController {dom
@RequestMapping(value="excel", method = RequestMethod.POST)
public String importOut(){this
SimpleDateFormat sdf2 = new SimpleDateFormat("yyyyMMdd");spa
SimpleDateFormat sdf_day = new SimpleDateFormat("yyyy-MM-dd");excel
String outPutPath=ServerUtil.UPLOAD_URL+sdf_day.format(new Date())+"\\";//建立臨時目錄orm
createOrder();//調用獲取全部訂單數據,以及生成Excel文檔!遞歸
//打成zip包ip
List<File> files = new ArrayList<File>();
File Allfile = new File(outPutPath);
if (Allfile.exists()) {
File[] fileArr = Allfile.listFiles();
for (File file2 : fileArr) {
files.add(file2);
}
}文檔
if(files.size()<1){
request.setAttribute("error","沒有可導出的文件!");
return "importout";
}
String fileName = sdf2.format(new Date())+ ".zip";//UUID.randomUUID().toString() + ".zip";
// 在服務器端建立打包下載的臨時文件
File fileZip = new File(outPutPath + fileName);
// 文件輸出流
FileOutputStream outStream = new FileOutputStream(fileZip);
// 壓縮流
ZipOutputStream toClient = new ZipOutputStream(outStream);
this.zipFile(files, toClient);
toClient.close();
outStream.close();
this.downloadFile(fileZip, response, false,Allfile);
//清除臨時目錄以及目錄下的文件
File file = new File(outPutPath);
deleteDir(file);
return "importout";
}
/**
*查詢所有訂單
*/
private void createOrder(){
List<OrderInfo> projects =orderService.searchOrderCSV();//調用service層 查詢得到全部訂單數據
String sheetName ="玩家訂單查詢";//定義excel名字
List<Map<String, String>> listmap = new ArrayList<Map<String, String>>();
OrderInfo order=null;
for (int j = 0; j < projects.size(); j++) {//把訂單數據集合 轉換爲 List<Map<String, String>>類型
order=projects.get(j);
Map<String, String> mapValue = new LinkedHashMap<String, String>();
mapValue.put("successTime", Loader.df.format(order.getSuccessTime()));
mapValue.put("oid", String.valueOf(order.getOid()));
mapValue.put("type",String.valueOf(order.getType()));
mapValue.put("num",String.valueOf(order.getNum()));
mapValue.put("sendRid",String.valueOf(order.getSendRid()));
mapValue.put("rid", String.valueOf(order.getRid()));
listmap.add(mapValue);
}
String columnNames[]={"時間","訂單號","類型","金條數量","發放人ID","玩家ID"};//列名
String keys[] = {"successTime","oid","type","num","sendRid","rid"};//map中的key
CSVUtils.createCSVFile(listmap,columnNames,keys,sheetName);//調用CSVUtils類中createCSVFile()方法生成excel文件
}
/**
* 下載文件
* @param file
* @param response
* @param isDelete
*/
public void downloadFile(File file,HttpServletResponse response,boolean isDelete,File Allfile) {
try {
// 以流的形式下載文件。
BufferedInputStream fis = new BufferedInputStream(new FileInputStream(file.getPath()));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
// 清空response
response.reset();
OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment;filename=" + new String(file.getName().getBytes("UTF-8"),"ISO-8859-1"));
toClient.write(buffer);
toClient.flush();
toClient.close();
if(isDelete)
{
file.delete(); //是否將生成的服務器端文件刪除
//System.out.println(Allfile.isFile());
if(Allfile.isDirectory()) {
File[] childFilePaths = Allfile.listFiles();
for(File childFile : childFilePaths){
//System.out.println("刪除:"+childFile.getName());
childFile.delete();
}
}
Allfile.delete();
}
}
catch (IOException ex) {
ex.printStackTrace();
}
}
public void zipFile(List<File> files, ZipOutputStream outputStream) throws IOException, ServletException {
try {
int size = files.size();
// 壓縮列表中的文件
for (int i = 0; i < size; i++) {
File file = (File) files.get(i);
zipFile(file, outputStream);
}
} catch (IOException e) {
throw e;
}
}
private static boolean deleteDir(File dir) {
if (dir.isDirectory()) {
String[] children = dir.list();
//遞歸刪除目錄中的子目錄下
for (int i=0; i<children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
return false;
}
}
}
// 目錄此時爲空,能夠刪除
return dir.delete();
}
}
public class CSVUtils {
public static File createCSVFile(List exportData,String columnNames[], String []keys,
String filename) {
SimpleDateFormat sdf_day = new SimpleDateFormat("yyyy-MM-dd");
String outPutPath=ServerUtil.UPLOAD_URL+sdf_day.format(new Date())+"\\";
File csvFile = null;
BufferedWriter csvFileOutputStream = null;
try {
csvFile = new File(outPutPath + filename + ".csv");
File parent = csvFile.getParentFile();
if (parent != null && !parent.exists()) {
parent.mkdirs();
}
csvFile.createNewFile();
// GB2312使正確讀取分隔符","
csvFileOutputStream = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(csvFile), "GB2312"), 1024);
// 寫入文件頭部
for(int i=0;i<columnNames.length;i++){
csvFileOutputStream.write("\""
+ columnNames[i].toString() + "\"");
csvFileOutputStream.write(",");
}
csvFileOutputStream.newLine();
// 寫入文件內容
for (Iterator iterator = exportData.iterator(); iterator.hasNext();) {
Object row = (Object) iterator.next();
for(int i=0;i<keys.length;i++){
csvFileOutputStream.write("\""
+ BeanUtils.getProperty(row,keys[i]).toString() + "\"");
csvFileOutputStream.write(",");
}
if (iterator.hasNext()) {
csvFileOutputStream.newLine();
}
}
csvFileOutputStream.flush();
} catch (Exception e) {
logger.error("Exception", e);
} finally {
try {
csvFileOutputStream.close();
} catch (IOException e) {
logger.error("IOException", e);
}
}
return csvFile;
}
}