excel (2)
阅读原文时间:2023年07月11日阅读:2

… poi 3.8

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.ss.util.RegionUtil;

/**
* Excel 工具类
*
* @author Administrator
*
*/
public class ExcelUtil2 {
//excel模板路径
//private static final String baseExcelModelUrl = System.getProperty("catalina.home") + "/webapps/fszfbz_v1";
private static final String baseExcelModelUrl = System.getProperty("catalina.home") + "/webapps/JZOA_V2/";

/\*\* 模板   \*\*/

/\*\*  
 \* 复制excel模板  
 \*  
 \* @throws FileNotFoundException  
 \* @throws IOException  
 \*/  
public static HSSFWorkbook importExcellModel(String excelurl) throws FileNotFoundException, IOException {  
    File file = new File(baseExcelModelUrl+excelurl);  
    InputStream is = new FileInputStream(file);  
    HSSFWorkbook wb = new HSSFWorkbook(is);  
    return wb;  
}

/\*\*  
 \* 根据workbook并插入数据  
 \* @param modelName  
 \* @param dataArray  
 \* @param fieldName  
 \* @throws FileNotFoundException  
 \* @throws IOException  
 \*/  
public static HSSFWorkbook createHSSFSheet(HSSFWorkbook wb,int sheetNum,int startRow,int startCol,List<Map<String,Object>> dataArray,String\[\] fieldName) throws FileNotFoundException, IOException{  
    HSSFSheet sheet;  
    HSSFCell cell;

    sheet = wb.getSheetAt(sheetNum);

    //导入数据  
    int rowNum = startRow-2;  
    sheet.shiftRows(rowNum+1, sheet.getPhysicalNumberOfRows(), dataArray.size());  
    HSSFCellStyle cellStyle = getCellStyle(wb);

    int colNum = startCol-2;  
    for (int i = 0; i < dataArray.size(); i++) {  
        //数据  
        Map<String, Object> dataMap = dataArray.get(i);  
        //创建行  
        HSSFRow row = sheet.createRow(++rowNum);  
        //数据列  
        for(int j=0;j<fieldName.length;j++){  
            cell = row.createCell(++colNum);  
            cell.setCellStyle(cellStyle);  
            if("序号".equals(fieldName\[j\])){//序号则输出相应序号  
                cell.setCellValue(i+1);  
                continue;  
            }  
            if("".equals(fieldName\[j\])){//字符串空则不填  
                continue;  
            }  
            Object cellValue = dataMap.get(fieldName\[j\]);  
            if(cellValue!=null){  
                cell.setCellValue(cellValue.toString());  
            }  
        }  
        colNum = startCol-2;  
    }  
    return wb;  
}

public static HSSFWorkbook createHSSFSheet(HSSFWorkbook wb,int startRow,int startCol,List<Map<String,Object>> dataArray,String\[\] fieldName) throws FileNotFoundException, IOException{  
    return createHSSFSheet(wb,0,startRow,startCol,dataArray,fieldName);  
}

/\*\*  
 \* 通过传入路径复制模板并设置数据  
 \*/  
public static HSSFWorkbook createHSSFSheet(String modelPath,int sheetNum,int startRow,int startCol,List<Map<String,Object>> dataArray,String\[\] fieldName) throws FileNotFoundException, IOException{  
    HSSFWorkbook wb = importExcellModel(modelPath);  
    createHSSFSheet(wb,sheetNum,startRow,startCol,dataArray,fieldName);  
    return wb;  
}  
/\*\*  
 \*  
 \* @param modelPath 路径  
 \* @param startRow  
 \* @param startCol  
 \* @param dataArray 数据  
 \* @param fieldName 文件名称???  
 \* @return  
 \* @throws FileNotFoundException  
 \* @throws IOException  
 \*/  
public static HSSFWorkbook createHSSFSheet(String modelPath,int startRow,int startCol,List<Map<String,Object>> dataArray,String\[\] fieldName) throws FileNotFoundException, IOException{  
    HSSFWorkbook wb = importExcellModel(modelPath);  
    createHSSFSheet(wb,0,startRow,startCol,dataArray,fieldName);  
    return wb;  
}

/\*\* 获取指定内容,无则创建 \*\*/

/\*\*  
 \* 获取指定行,若指定行未创建则创建  
 \* @param sheet  
 \* @param rowNum  
 \* @return  
 \*/  
public static HSSFRow getHSSFRow(HSSFSheet sheet,Integer rowNum){  
    HSSFRow row = sheet.getRow(rowNum);  
    if (row == null) {  
        row = sheet.createRow(rowNum);  
    }  
    return row;  
}

/\*\*  
 \* 获取指定单元格,若指定单元格未创建则创建  
 \* @param sheet  
 \* @param rowNum  
 \* @return  
 \*/  
public static HSSFCell getHSSFCell(HSSFSheet sheet,Integer rowNum,Integer colNum){  
    HSSFRow row = getHSSFRow(sheet,rowNum);  
    HSSFCell cell = row.getCell(colNum);  
    if (cell == null) {  
        cell = row.createCell(colNum);  
    }  
    return cell;  
}

/\*\*  
 \* 获取指定单元格,若指定单元格未创建则创建  
 \* @param sheet  
 \* @param rowNum  
 \* @return  
 \*/  
public static HSSFCell getHSSFCell(HSSFRow row,Integer colNum){  
    HSSFCell cell = row.getCell(colNum);  
    if (cell == null) {  
        cell = row.createCell(colNum);  
    }  
    return cell;  
}

/\*\* 数据替换   \*\*/

/\*\*  
 \* 替换表格${}数据  
 \*  
 \* @param replaceDataMap  
 \* @param sheet  
 \*/  
public static void replaceCellValue(Map<String, Object> replaceDataMap,HSSFSheet sheet) {  
    replaceCellValue(replaceDataMap,sheet,0);  
}

public static void replaceCellValue(Map<String, Object> replaceDataMap,HSSFSheet sheet,int checkRowNum) {  
    Iterator rows = sheet.rowIterator();  
    while (rows.hasNext()) {  
        HSSFRow row = (HSSFRow) rows.next();  
        if (row != null) {  
            int num = row.getLastCellNum();  
            if(checkRowNum-1>=0){  
                if (row.getRowNum() > checkRowNum-1) {  
                    break;  
                }  
            }  
            for (int i = 0; i < num; i++) {  
                HSSFCell cell = row.getCell(i);  
                if (cell == null || cell.getStringCellValue() == null) {  
                    continue;  
                }  
                String cellValue = cell.getStringCellValue();

                if (!"".equals(cellValue)) {  
                    if (cellValue.indexOf('$') != -1) {  
                        cell.setCellValue(getReplaceValue(cellValue,replaceDataMap));  
                    }  
                } else {  
                    cell.setCellValue("");  
                }  
            }  
        }  
    }  
}

/\*\*  
 \* 从replaceDataMap中获取${XX}对应要替换的数据  
 \* @param cellValue        ${}名称(每$待办要替换一个数据)  
 \* @param replaceDataMap    包含要用于替换数据的map  
 \* @return  
 \*/  
private static String getReplaceValue(String cellValue,Map<String, Object> replaceDataMap) {

    // 获取$出现的次数。  
    int num = 0;  
    for (int i = 0; i < cellValue.length(); i++) {  
        if ("$".equals(cellValue.substring(i, i + 1))) {  
            num++;  
        }  
    }  
    for (int i = 0; i < num; i++) {  
        String str = cellValue.substring(cellValue.indexOf('{') + 1,cellValue.indexOf('}'));  
        if (null == replaceDataMap.get(str)) {  
            cellValue = cellValue.replace("${" + str + "}", "");  
        } else {  
            cellValue = cellValue.replace("${" + str + "}",  
            (String) replaceDataMap.get(str));  
        }  
    }  
    return cellValue;  
}

/\*\*  
 \* 设置建表时间  
 \* c\_t\_year 建表时间-年  
 \* c\_t\_mouth 建表时间-月  
 \* c\_t\_day 建表时间-日  
 \* @param sheet  
 \*/  
private static void setCreateTime(HSSFSheet sheet){  
    //设置建表时间数据  
    Calendar c = Calendar.getInstance();  
    int year = c.get(Calendar.YEAR);  
    int mouth = c.get(Calendar.MONTH) + 1;  
    int day = c.get(Calendar.DAY\_OF\_MONTH);  
    Map<String, Object> replaceDataMap = new HashMap<String, Object>();  
    replaceDataMap.put("c\_t\_year", String.valueOf(year));  
    replaceDataMap.put("c\_t\_mouth", String.valueOf(mouth));  
    replaceDataMap.put("c\_t\_day",String.valueOf(day));  
    //替换  
    replaceCellValue(replaceDataMap, sheet);  
}

/\*\* 坐标   \*\*/

//x轴坐标+1  
private static final Map<Character, Integer> excelXAddr = new HashMap<Character, Integer>(){  
    {  
        put('A',1);put('B',2);put('C',3);put('D',4);put('E',5);put('F',6);  
        put('G',7);put('H',8);put('I',9);put('J',10);put('K',11);put('L',12);  
        put('M',13);put('N',14);put('O',15);put('P',16);put('Q',17);  
        put('R',18);put('S',19);put('T',20);put('U',21);put('V',22);  
        put('W',23);put('X',24);put('Y',25);put('Z',26);  
    }  
};

/\*\*  
 \* 根据坐标获取X坐标对应的索引  
 \* @param xName  
 \* @return  
 \*/  
public static final Integer getXAddr(String xName){  
    Integer xAddr = 0;  
    if(xName!=null && xName!=""){  
        char\[\] xNameList = xName.toCharArray();  
        xAddr = excelXAddr.get(xNameList\[0\]);  
        for(int i=1;i<xNameList.length;i++){  
            xAddr = xAddr\*26+excelXAddr.get(xNameList\[i\]);  
        }  
    }  
    return --xAddr;  
}

/\*\* 单元格合并   \*\*/

/\*\*  
 \* 多次合并单元格  
 \* @param sheet 需要合并的工作表对象  
 \* @param mergedAddress2D 单次合并单元格数组的数组  
 \*/  
public static void mergedAddress(HSSFSheet sheet,String \[\]\[\] mergedAddress2D){  
    for(String\[\] mergedAddress:mergedAddress2D){  
        mergedAddress(sheet ,mergedAddress);  
    }  
}

/\*\*  
 \* 一次合并单元格  
 \* @param sheet 需要合并的工作表对象  
 \* @param mergedAddress 如:{"1","A","1","K"}前两个为左上角单元格,后两个值为右下角单元格  
 \*/  
public static void mergedAddress(HSSFSheet sheet,String \[\] mergedAddress){  
    //x轴开始坐标  
    int xsA = getXAddr(mergedAddress\[1\]);  
    //x轴结束坐标  
    int xeA = getXAddr(mergedAddress\[3\]);  
    sheet.addMergedRegion(new CellRangeAddress(Integer.valueOf(mergedAddress\[0\]).intValue()-1,Integer.valueOf(mergedAddress\[2\]).intValue()-1,--xsA,--xeA));  
}

/\*\*  
 \* 多次合并单元格,并可设置合并单元格属性  
 \* @param sheet 需要合并的工作表对象  
 \* @param mergedAddress2D 单次合并单元格数组的数组  
 \*/  
public static void mergedAddress(HSSFWorkbook wb,int sheetNum,List<Map<String,String>> mergedAddressList){  
    HSSFSheet sheet = wb.getSheetAt(sheetNum);  
    for(Map<String,String> mergedAddress:mergedAddressList){  
        Integer ys = Integer.valueOf(mergedAddress.get("ys"));  
        Integer xs = Integer.valueOf(mergedAddress.get("xs"));  
        Integer ye = Integer.valueOf(mergedAddress.get("ye"));  
        Integer xe = Integer.valueOf(mergedAddress.get("xe"));  
        //合并单元格  
        CellRangeAddress cellRangeAddress = mergedAddress(sheet,ys,xs,ye,xe);

        //获取指定单元格  
        HSSFCell cell = getHSSFCell(sheet,ys,xs);  
        //查看是否需要设置单元格属性  
        String cellStyle = mergedAddress.get("cellStyle");  
        if(null!=cellStyle){  
            HSSFCellStyle HSSFCS = getCellStyle(wb,cellStyle);  
            cell.setCellStyle(HSSFCS);  
            //setBorderForMergeCell(CellStyle.BORDER\_THIN,cellRangeAddress,0,wb);  
        }

        //查看是否需要设置字体属性  
        String fontStyle = mergedAddress.get("fontStyle");  
        if(null!=fontStyle){  
            HSSFFont HSSFF = getFontStyle(wb,fontStyle);  
            HSSFCellStyle HSSFCS = cell.getCellStyle();  
            HSSFCS.setFont(HSSFF);  
            cell.setCellStyle(HSSFCS);  
        }

        //查看是否需要设置单元格内容  
        String content = mergedAddress.get("content");  
        if(null!=content){  
            cell.setCellValue(content);  
        }  
    }  
}

/\*\*  
 \* 一次合并单元格  
 \* @param sheet 需要合并的工作表对象  
 \* @param ys y轴开始坐标(左上角单元格y轴)  
 \* @param xs x轴开始坐标(左上角单元格x轴)  
 \* @param ye y轴结束坐标(右下角单元格y轴)  
 \* @param xe x轴结束坐标(右下角单元格x轴)  
 \*  
 \*/  
public static CellRangeAddress mergedAddress(HSSFSheet sheet,int ys,int xs,int ye,int xe){  
    CellRangeAddress cellRangePlanNo = new CellRangeAddress( ys, ye, xs, xe );  
    sheet.addMergedRegion(cellRangePlanNo);  
    return cellRangePlanNo;  
}

/\*\* 工具   \*\*/

//自动获取单元格高度  
public static float getExcelCellAutoHeight(String str, float fontCountInline) {  
    float defaultRowHeight = 12.00f;// 每一行的高度指定  
    float defaultCount = 0.00f;  
    for (int i = 0; i < str.length(); i++) {  
        float ff = getregex(str.substring(i, i + 1));  
        defaultCount = defaultCount + ff;  
    }  
    return ((int) (defaultCount / fontCountInline) + 1) \* defaultRowHeight;// 计算  
}

public static float getregex(String charStr) {  
    if (charStr == " ") {  
        return 0.5f;  
    }  
    // 判断是否为字母或字符  
    if (Pattern.compile("^\[A-Za-z0-9\]+$").matcher(charStr).matches()) {  
        return 0.5f;  
    }

    // 判断是否为全角  
    if (Pattern.compile("\[\\u4e00-\\u9fa5\]+$").matcher(charStr).matches()) {  
        return 1.00f;  
    }

    // 全角符号 及中文  
    if (Pattern.compile("\[^x00-xff\]").matcher(charStr).matches()) {  
        return 1.00f;  
    }  
    return 0.5f;  
}

/\*\* 字体/单元格style \*\*/

/\*\*  
 \* 获取单元格风格  
 \* @param wb  
 \* @return  
 \*/  
public static HSSFCellStyle getCellStyle(HSSFWorkbook wb,String styleName){  
    HSSFCellStyle cellStyle = null;  
    if("".equals(styleName)){

    }else{  
        cellStyle = wb.createCellStyle();  
        cellStyle.setWrapText(true);  
        cellStyle.setAlignment(CellStyle.ALIGN\_CENTER);// 水平居中  
        cellStyle.setVerticalAlignment(CellStyle.VERTICAL\_CENTER);// 垂直居中  
        cellStyle.setBorderBottom((short) 1);  
        cellStyle.setBorderLeft((short) 1);  
        cellStyle.setBorderRight((short) 1);  
        cellStyle.setBorderTop((short) 1);  
    }  
    return cellStyle;  
}

/\*\*  
 \* 获取默认单元格风格  
 \* @param wb  
 \* @return  
 \*/  
public static HSSFCellStyle getCellStyle(HSSFWorkbook wb){  
    return getCellStyle(wb,null);  
}

/\*\*  
 \* 获取单元格风格  
 \* @param wb  
 \* @return  
 \*/  
public static HSSFFont getFontStyle(HSSFWorkbook wb,String styleName){  
    HSSFFont fontStyle = null;  
    if("left\_title\_1".equals(styleName)){  
        fontStyle = wb.createFont();  
        fontStyle.setFontName("宋体");  
        fontStyle.setBoldweight(HSSFFont.BOLDWEIGHT\_BOLD);//粗体显示  
        fontStyle.setFontHeightInPoints((short) 12);//设置字体大小  
    }else{

    }  
    return fontStyle;  
}

/\*\*  
 \* 获取默认单元格风格  
 \* @param wb  
 \* @return  
 \*/  
public static HSSFFont getFontStyle(HSSFWorkbook wb){  
    return getFontStyle(wb,null);  
}

/\*\*  
 \* 设置合并单元格边框  
 \* @param i  
 \* @param cellRangeTitle  
 \* @param sheet  
 \* @param workBook  
 \*/  
private static void setBorderForMergeCell(int i, CellRangeAddress cellRangeAddress, int sheetNum, HSSFWorkbook wb){  
    RegionUtil.setBorderBottom(i, cellRangeAddress, wb.getSheetAt(sheetNum), wb);  
    RegionUtil.setBorderLeft(i, cellRangeAddress, wb.getSheetAt(sheetNum), wb);  
    RegionUtil.setBorderRight(i, cellRangeAddress, wb.getSheetAt(sheetNum), wb);  
    RegionUtil.setBorderTop(i, cellRangeAddress, wb.getSheetAt(sheetNum), wb);  
}

/\*\*  
 \* 输出信息到页面  
 \* @param response  
 \* @param Msg  
 \*/  
public static void writeMsgToHtml(HttpServletResponse response, String Msg) {  
    try {  
        response.setContentType("text/html;charset=utf-8");  
        PrintWriter out = response.getWriter();  
        out.write(Msg);  
        out.close();  
    } catch (Exception ex) {  
        ex.printStackTrace();  
    }  
}

/\*\* 文件传输   \*\*/

/\*\*  
 \* 用HSSFWorkbook生成excel文件在服务器  
 \* @param excelName  
 \* @param wb  
 \* @throws FileNotFoundException  
 \* @throws IOException  
 \*/  
public static boolean generateExcel(String fileName, HSSFWorkbook wb) throws FileNotFoundException, IOException {  
    try {  
        // 输出文件  
        String writeExcelUrl = System.getProperty("catalina.home") + "/webapps/webdav/" + fileName+".xls";  
        File fileOut = new File(writeExcelUrl);  
        FileOutputStream os = new FileOutputStream(fileOut);  
        wb.write(os);  
        close(os);  
    } catch (IOException e) {  
        // TODO Auto-generated catch block  
        //e.printStackTrace();  
        return false;  
    }  
    return true;  
}

/\*\*  
 \* 用HSSFWorkbook生成excel文件在服务器  
 \* @param excelName  
 \* @param wb  
 \* @throws FileNotFoundException  
 \* @throws IOException  
 \*/  
public static String generateExcel2(String fileName, HSSFWorkbook wb) throws FileNotFoundException, IOException {  
    String dz = "";  
    try {  
        // 输出文件  
        String writeExcelUrl = System.getProperty("catalina.home") + "/webapps/webdav/" + fileName+".xls";  
        File fileOut = new File(writeExcelUrl);  
        FileOutputStream os = new FileOutputStream(fileOut);  
        wb.write(os);  
        close(os);  
        dz = fileName+".xls";  
    } catch (IOException e) {  
        // TODO Auto-generated catch block  
        //e.printStackTrace();  
        return "";  
    }  
    return dz;  
}

/\*\*  
 \* 用HSSFWorkbook生成excel文件给用户下载  
 \* @param excelName  
 \* @param wb  
 \* @throws IOException  
 \* @throws FileNotFoundException  
 \* @throws IOException  
 \*/  
public static boolean generateExcel(HttpServletResponse response,String fileName, HSSFWorkbook wb){  
    try {  
        setResponseHeader(response, fileName);  
        OutputStream os = response.getOutputStream();  
        wb.write(os);  
        close(os);  
    } catch (IOException e) {  
        // TODO Auto-generated catch block  
        //e.printStackTrace();  
        return false;  
    }  
    return true;  
}

/\*\*  
 \* 关闭输出流  
 \* @param os  
 \*/  
private static void close(OutputStream os) {  
    if (os != null) {  
        try {  
            os.flush();  
            os.close();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
    }  
}

/\*\*  
 \* 发送响应流方法  
 \* @param response  
 \* @param fileName  
 \*/  
public static void setResponseHeader(HttpServletResponse response, String fileName) {  
    try {  
        try {  
            fileName = new String((fileName+".xls").getBytes("UTF-8"),"ISO8859-1");  
            //fileName = new String(fileName.getBytes(),"ISO8859-1");  
        } catch (UnsupportedEncodingException e) {  
            e.printStackTrace();  
        }  
        response.reset();  
        response.setContentType("application/msexcel");  
        //response.setContentType("application/octet-stream;charset=ISO8859-1");  
        response.setHeader("Content-Disposition", "attachment;filename="+ fileName);  
        response.addHeader("Pargam", "no-cache");  
        response.addHeader("Cache-Control", "no-cache");  
    } catch (Exception ex) {  
        ex.printStackTrace();  
    }  
}

/\*\*  
 \* xls打包成zip进行下载  
 \*/  
public String downloads(String\[\] filepath, HttpServletResponse response,String name) throws IOException, ServletException {  
    Date day = new Date();  
    SimpleDateFormat df = new SimpleDateFormat("HHmmss");  
    // 要生成的压缩文件地址和文件名称  
    String fileName = name + df.format(day) + ".zip";  
    String path = System.getProperty("catalina.home") + "/webapps/webdav/" + fileName;  
    File zipFile = new File(path);  
    ZipOutputStream zipStream = null;  
    FileInputStream zipSource = null;  
    BufferedInputStream bufferStream = null;  
    try {  
        // 构造最终压缩包的输出流  
        zipStream = new ZipOutputStream(new FileOutputStream(zipFile));  
        for (int i = 0; i < filepath.length; i++) {  
            File file = new File(System.getProperty("catalina.home")  
                    + "/webapps/webdav/" + filepath\[i\]);  
            // 将需要压缩的文件格式化为输入流  
            zipSource = new FileInputStream(file);  
            // 压缩条目不是具体独立的文件,而是压缩包文件列表中的列表项,称为条目,就像索引一样  
            ZipEntry zipEntry = new ZipEntry(file.getName());  
            // 定位该压缩条目位置,开始写入文件到压缩包中  
            zipStream.putNextEntry(zipEntry);  
            // 输入缓冲流  
            bufferStream = new BufferedInputStream(zipSource, 1024 \* 10);  
            int read = 0;  
            // 创建读写缓冲区  
            byte\[\] buf = new byte\[1024 \* 10\];  
            while ((read = bufferStream.read(buf, 0, 1024 \* 10)) != -1) {  
                zipStream.write(buf, 0, read);  
            }  
        }  
    } catch (Exception e) {  
        e.printStackTrace();  
    } finally {  
        // 关闭流  
        try {  
            if (null != bufferStream)  
                bufferStream.close();  
            if (null != zipStream)  
                zipStream.close();  
            if (null != zipSource)  
                zipSource.close();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
    }

    return fileName;  
    /\*  
     \* //2.获取要下载的文件名 String fileName =  
     \* path.substring(path.lastIndexOf("\\\\")+1);  
     \* //3.设置content-disposition响应头控制浏览器以下载的形式打开文件 File fi=new File(path);  
     \* response.setHeader("Content-Disposition",  
     \* "attachment;filename="+URLEncoder.encode(fileName, "UTF-8"));  
     \* response.addHeader("Content-Length", "" + fi.length());  
     \* response.setContentType("application/octet-stream"); //4.获取要下载的文件输入流  
     \* InputStream in = new FileInputStream(fi); int len = 0; //5.创建数据缓冲区  
     \* byte\[\] buffer = new byte\[1024\]; //6.通过response对象获取OutputStream流  
     \* OutputStream out = response.getOutputStream();  
     \* //7.将FileInputStream流写入到buffer缓冲区 while ((len = in.read(buffer)) > 0)  
     \* { //8.使用OutputStream将缓冲区的数据输出到客户端浏览器 out.write(buffer,0,len); }  
     \* in.close();  
     \*/  
}

public static void main(String\[\] args) {

}  

}

// (后台调用的方法部分)
List> sj = dBSelect(sql);

    //文件名  
    SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");  
    Date today = new Date();  
    String appId ="ZB-"; // 中文不行  
    //b=b.replace("b","");

    appId += format.format(today);//.replace("-","").replace(":","").replace(" ","")

    String \[\] sxm = {"序号","xmmc", "problemContent", "selfCheckingSituation", "","endTime","","completion",""};  
    // xmmc, problem\_content, self\_checking\_situation, '', end\_time,'',completion,""  
    // 所属项目    工作内容                  完成结果                     完成状态    完成时间    协助人    已达成结果和完成程度    备注  
    if(sj !=null && !sj.isEmpty()){  
        HSSFWorkbook wb = ExcelUtil2.importExcellModel("/excelModel/WeeklyTemplate.xls");  // 由于 $ 部分需要替换  
        ExcelUtil2.replaceCellValue(replaceDataMap,wb.getSheetAt(0),5); // 创建一个Excel文件  
        wb = ExcelUtil2.createHSSFSheet(wb,0, 5,1, sj,sxm); // 创建一个Excel文件 

        /\*HSSFWorkbook wb = ExcelUtil2.createHSSFSheet("/excelModel/rent\_collection\_import.xls", 2, 1, list, fieldName);  \*/  
        String ming = ExcelUtil2.generateExcel2(appId,wb); // generateExcel(response对象,导出文件的名字,wb)  
        //ExcelUtil2.generateExcel(getResponse(),appId,wb); // 不用ajax 的方式,其不用返回什么  
        try{  
             if(!ming.equals("")){  
                 //导出成功  
                 returnMap.put("ming", ming);  
             }  
        }catch (Exception e) {  
            returnMap.put("status", "-1");  
            //e.printStackTrace();  
        }

function exportExcel(){ //不用ajax
var large = mini.get("large").getText();
var Small = mini.get("Small").getText();
if(large != null && Small !=null && large != "" && Small !="" ){
console.log(large);
window.open("<%=basePath %>exportExcel/exportExcel.do?large="+large+"&Small="+Small);
}else{
alert("请输入开始时间与截止时间!!!");
}

}  
function exportExcel\_ajax(){ //用ajax(可以传复杂的参数)  
    //alert("!!!!!!!!!!!!!");  
    var large = mini.get("large").getText();  
    var Small = mini.get("Small").getText();  
    if(large != null && Small !=null && large != "" && Small !="" ){  
        $.ajax({  
            url: "<%=basePath %>exportExcel/exportExcel.do",  
            data: {large:large,Small:Small},  
            type: "post",  
            dataType:'json',  
            success: function (text) {  
                if(text.status == '-1') {  
                    //console.log("");  
                    mini.alert("导出失败或无数据!");  
                }else{  
                    var ming = text.ming;  
                    <%String webdav = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+"/webdav/";%>  
                    window.open("<%=webdav%>"+ming);  
                }

            },  
            error: function (jqXHR, textStatus, errorThrown) {  
                //alert(jqXHR.responseText);  
                //cancel(); //关闭窗口  
                mini.alert("导出异常!");  
            }  
        });  
    }else{  
        alert("请输入开始时间与截止时间!!!");  
    }  
}

手机扫一扫

移动阅读更方便

阿里云服务器
腾讯云服务器
七牛云服务器

你可能感兴趣的文章