Generate and download Ecxel files in java (public)

Source: Internet
Author: User

Generate and download Ecxel files in java (public)

/*** Shanghai Automotive Group Financial Co., Ltd. * Copyright (c) 1994-2014 All RightsReserved. */package com. saicfc. pmpf. internal. manage. utils; import java. io. file; import java. io. IOException; import java. util. iterator; import java. util. linkedHashMap; import java. util. list; import jxl. workbook; import jxl. write. label; import jxl. write. writableSheet; import jxl. write. writableWorkbook; import jxl. write. writeException; import jxl. write. bif F. rowsExceededException;/*** Excel file builder * @ author lizhiyong * @ version $ Id: ExcelUtils. java, v 0.12014-September 11 5:27:18 Exp $ */public class ExcelUtils {/*** generate an Excel file jxl * @ param filePath the path of the Excel file to be generated * @ param titleList * @ param dataList detailed information of the Excel file to be generated * @ param fileName the Excel file name to be generated * @ param sheetName the sheet file name to be generated * @ return excelFile * // @ SuppressWarnings ("rawtypes ") publi C static File writeExcel (String filePath, List titleList, List dataList, String fileName, String sheetName) {WritableWorkbook wwb = null; File excelFile = null; try {File file = new File (filePath); if (! File. exists () {file. mkdir (); System. out. println ("folder created");} // create a jxl File // define the File name format and create excelFile = File. createTempFile (fileName ,". xls ", new File (filePath); // use the Workbook class factory method to create a writeable Workbook object wwb = Workbook. createWorkbook (excelFile); if (wwb! = Null) {// create a writable worksheet // The createSheet method of the Workbook has two parameters. The first one is the worksheet name, the second is the position of the worksheet in the workbook WritableSheet ws = wwb. createSheet (sheetName, 0); // Add the header information int row = 0; for (Iterator iterator = titleList. iterator (); iterator. hasNext ();) {LinkedHashMap titleMap = (LinkedHashMap) iterator. next (); int cell = 0; for (Iterator titleIterator = titleMap. entrySet (). iterator (); titleIterator. hasNext ();) {java. util. map. entry titleEntry = (java. util. map. entry) titleIterator. next (); // note that in Excel, the first parameter table represents the column, and the second parameter represents the row ws. addCell (new jxl. write. label (cell, row, (String) titleEntry. getValue (); cell ++;} row ++;} // Add the cell information int rows = titleList. size (); for (Iterator iterator = dataList. iterator (); iterator. hasNext ();) {LinkedHashMap dataMap = (LinkedHashMap) iterator. next (); int cells = 0; for (Iterator dataIterator = dataMap. entrySet (). iterator (); dataIterator. hasNext ();) {java. util. map. entry dataEntry = (java. util. map. entry) dataIterator. next (); // note that in Excel, the first parameter table represents the column, and the second indicates the row // Add the generated cells to the worksheet ws. addCell (new jxl. write. label (cells, rows, (String) dataEntry. getValue (); cells ++;} rows ++;} // write wwb to the file from the memory. write (); // close the resource and release the memory wwb. close () ;}} catch (IOException e) {e. printStackTrace ();} catch (RowsExceededException e) {e. printStackTrace ();} catch (WriteException e) {e. printStackTrace ();} return excelFile ;}}

The following is a call:

 

String fileName = "CITIC Bank (CITIC) Refund data"; String sheetName = "CITIC Bank (CITIC) Refund data"; List titleList = new ArrayList (); LinkedHashMap titleMap = new LinkedHashMap (); titleMap. put ("fileType", "file type:"); titleMap. put ("fileType1", "FTB2CBatchPayback"); titleList. add (0, titleMap); LinkedHashMap titleMap2 = new LinkedHashMap (); titleMap2.put ("fileTitle", "title:"); titleMap2.put ("fileTitle1", "refund batch "); titleList. add (1, titleMap2); titleList. add (2, new LinkedHashMap (); titleList. add (3, new LinkedHashMap (); LinkedHashMap titleMap3 = new LinkedHashMap (); titleMap3.put ("title1", "original payment order number"); titleMap3.put ("title2 ", "original payment order date"); titleMap3.put ("title3", "refund amount"); titleMap3.put ("title4", "summary"); titleList. add (4, titleMap3); // create a File file = ExcelUtils. writeExcel (filePath, titleList, exportData, fileName, sheetName); // download the downLoadFile (response, filePath, file );

/*** Download file ** @ param response * @ param filePath File path * @ param file * @ throws IOException */public void downLoadFile (HttpServletResponse response, String filePath, File file) throws IOException {String fileName = file. getName (); // download the file FileManageUtils. exportFile (response, filePath + fileName, fileName); // delete a single file FileManageUtils. deleteFile (filePath, fileName );}

Package com. saicfc. pmpf. internal. manage. utils; import java. io. file; import java. io. fileInputStream; import java. io. fileNotFoundException; import java. io. IOException; import java. io. inputStream; import java. io. outputStream; import javax. servlet. http. httpServletResponse;/*** file management ** @ author lizhiyong * @ version $ Id: FileManageUtils. java, v 0.12014-September 11 9:37:47 Exp $ */public class FileManageUtils {/*** Download file * @ param response * @ param csvFilePath * file path * @ param fileName * file name * @ throws IOException */public static void exportFile (HttpServletResponse response, String csvFilePath, String fileName) throws IOException {response. setContentType ("application/csv; charset = GBK"); response. setHeader ("Content-Disposition", "attachment; filename =" + new String (fileName. getBytes ("GBK"), "ISO8859-1"); // UR LEncoder. encode (fileName, "GBK") InputStream in = null; try {in = new FileInputStream (csvFilePath); int len = 0; byte [] buffer = new byte [1024]; response. setCharacterEncoding ("GBK"); OutputStream out = response. getOutputStream (); while (len = in. read (buffer)> 0) {// out. write (new byte [] {(byte) 0xEF, (byte) 0xBB, (byte) 0xBF}); out. write (buffer, 0, len) ;}} catch (FileNotFoundException e ){ System. out. println (e);} finally {if (in! = Null) {try {in. close () ;}catch (Exception e) {throw new RuntimeException (e );}}}} /*** delete all files under the filePath directory * @ param filePath * File directory path */public static void deleteFiles (String filePath) {file File = new file (filePath ); if (file. exists () {File [] files = file. listFiles (); for (int I = 0; I <files. length; I ++) {if (files [I]. isFile () {files [I]. delete () ;}}}/*** delete a single file * @ param filePath * file directory path * @ param fileName * file name */public static void deleteFile (String filePath, string fileName) {File file = new File (filePath); if (file. exists () {File [] files = file. listFiles (); for (int I = 0; I <files. length; I ++) {if (files [I]. isFile () {if (files [I]. getName (). equals (fileName) {files [I]. delete (); return ;}}}}}}


 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.