【demo】Excel批量設置超鏈接(java代碼實現)

背景:某同學找到我,問我能不能幫忙寫個代碼,批量設置excel的超鏈接(excel有文件名)。然後立馬想到poi,這不是很簡單嗎。於是寫了個小demo,最後也被同學稱讚牛逼(我就深藏功與名的微笑.jpg)

PS:建議將excel文件改爲xls文件

以下是代碼:

前端js上傳代碼太簡單了,一個ajax上傳即可,只展示controller代碼。

 


@Controller
@RequestMapping(value = "/test/excel")
public class TestExcelController {

    @RequestMapping(value = "/uploadFile.do", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> uploadReportBiFile(HttpServletRequest request,HttpServletResponse response, MultipartFile file) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        resultMap.put("result", "success");
        try {
            InputStream inputStream = null;
            Workbook workbook = null;
            try {
                inputStream = file.getInputStream();
                String fileAllName = file.getOriginalFilename();
                String fileName=fileAllName.substring(0,fileAllName.lastIndexOf("."));
                int type=0;
                String targetFilePath="./pdf/";//excel文件目錄下的pdf文件夾
                
                //建議用xls文件
                if (fileAllName.endsWith(".xls")) {
                    workbook = new HSSFWorkbook(inputStream);
                    type=2;
                } else if (fileAllName.endsWith(".xlsx")) {//不建議使用
                    workbook = new XSSFWorkbook(inputStream);
                    type=1;
                } else {
                    resultMap.put("result", "error");
                    resultMap.put("message", "文件必須爲xls或者xlsx");
                    return resultMap;
                }

                //假設數據在第1個sheet,並且是從第一列的第二行開始,
                Sheet sheet = workbook.getSheetAt(0);
                for (Row row : sheet) {
                    Integer rowIndex = row.getRowNum(); // 行索引
                    if (rowIndex == 0 || rowIndex>1000) {//第1行是標題跳過,假設最多1000個數據
                        continue; // 這裏的if沒太多作用,只是爲了不讓循環太多次,節約時間
                    }
                    try {
                        Cell cell = row.getCell(0);//第1列
                        if (cell!=null) {
                            String name = getCellValue(cell);
                            if (name!=null) {
                                String namef=name+".pdf";
                                if (type==1) {//xlsx
                                    //這種方式不建議使用,因爲框裏會顯示函數
                                    cell.setCellType(HSSFCell.CELL_TYPE_FORMULA);
                                    cell.setCellFormula("HYPERLINK(\"" + targetFilePath+namef+  "\",\"" + name+"\")");
                                    cell.setCellValue(name);
                                    CellStyle linkStyle = workbook.createCellStyle();
                                    Font cellFont= workbook.createFont();
                                    cellFont.setUnderline(HSSFFont.U_SINGLE);
                                    cellFont.setColor(HSSFColor.BLUE.index);
                                    cellFont.setFontHeightInPoints((short)10);//font size
                                    linkStyle.setFont(cellFont);
                                    cell.setCellStyle(linkStyle);
                                    
                                }
                                if (type==2) {//xls
                                    //建議使用這種
                                    CellStyle  linkStyle = workbook.createCellStyle();
                                    Font  cellFont =  workbook.createFont();
                                    cellFont.setUnderline(HSSFFont.U_SINGLE);
                                    cellFont.setColor(HSSFColor.BLUE.index); 
                                    cellFont.setFontHeightInPoints((short)10);//font size
                                    linkStyle.setFont(cellFont);
                                    cell.setCellValue(name);
                                    Hyperlink link = cell.getHyperlink();
                                    link = new HSSFHyperlink(HSSFHyperlink.LINK_FILE);
                                    link.setAddress(targetFilePath+namef);
                                    cell.setHyperlink(link);
                                    cell.setCellStyle(linkStyle);
                                }
                            }
                        }
                    } catch (Exception e) {
                        // 解析失敗
                        e.printStackTrace();
                    }
                }
                //寫到本地
                File newFile=new File("D:/test");      
                OutputStream stream=null;
                try {
                    stream = new FileOutputStream(new File(newFile, new Date().getTime()+"-"+fileAllName));
                    workbook.write(stream);
                } catch (Exception e) {
                    e.printStackTrace();
                }finally{
                    try {
                        if(stream != null);
                            stream.close();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }    
                System.out.println("--------------------success---------------------");
            }catch(Exception e){
                e.printStackTrace();
            }
        } catch (Exception e) {
            resultMap.put("result", "error");
            resultMap.put("message", e.getMessage() + ",發生錯誤");
        }
        return resultMap;
    }
    
     /**  
    *
    * <p>Title: getCellValue</p>  
    *
    * <p>Description: 獲取excel的單元的值</p>  
    *
    * @param cell
    * @return  
    *
    */
   public static String getCellValue(Cell cell) {
       if(null == cell){
           return "";
       }
       if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
           // 返回布爾類型的值
           return String.valueOf(cell.getBooleanCellValue());
       } else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
           // 返回數值類型的值
           return String.valueOf((int)cell.getNumericCellValue());
       } else {
           cell.setCellType(Cell.CELL_TYPE_STRING);
           String cellValue = cell.getStringCellValue();
           if(null != cellValue){
               cellValue = cellValue.trim();
           }
           // 返回字符串類型的值
           return String.valueOf(cellValue);
       }
   }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章