中文字幕av专区_日韩电影在线播放_精品国产精品久久一区免费式_av在线免费观看网站

溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

poi導出word表格的操作講解

發布時間:2020-10-02 05:16:04 來源:腳本之家 閱讀:183 作者:Z丶royAl 欄目:開發技術

一、效果如下

poi導出word表格的操作講解

二、js代碼

function export_word(){ //導出word
  var url = "czzsca/exportWord.do";
  this.export(url);
}
function export(url){
  var currentyear = $("#mainYear").val() * 1;
  var key_columns = ['xh',"d_name","d_unit","d_number","d_estimate","d_lastyear","jnjh","d_remarks","d_depart","d_executeunit"];
  var value_columns = ['序號','項目名稱','單位','數量','總概算','至'+(currentyear-1)+'年完成',currentyear+'年計劃','附注','責任部門','計劃執行單位'];
  window.location.href= url+"?key_columns="+key_columns+"&value_columns="+value_columns+"&title="+currentyear+"年 更新改造計劃 正式計劃草案";
}

三、controller代碼

(controller代碼比較長,主要是格式化每一行的數據,主要是往工具類里傳List<List<String>>參數,泛型的List<String>是每一行,String是每一列)

 //導出word
 @RequestMapping("/exportWord.do")
 @ResponseBody
 public ReturnMsg exportWord(String[] key_columns,String[] value_columns,String title,HttpServletResponse response){
 ReturnMsg rm = new ReturnMsg();
 try {
  response.setCharacterEncoding("UTF-8");
     response.setContentType("application/msexcle");  
     response.setHeader("content-disposition", "attachment;filename="+new String("正式計劃草案".getBytes("gb2312"),"ISO8859-1")+".doc");
     List<List<String>> content = new ArrayList<List<String>>();
     List<List<String>> head = new ArrayList<List<String>>();
     String jnjhzh = new BigDecimal(this.map.get("jnjhzh")==null||"".equals(this.map.get("jnjhzh")+"")?"0":this.map.get("jnjhzh")+"").setScale(1, RoundingMode.UP)+"";
     String trimpro = new BigDecimal(this.map.get("tzjh")==null||"".equals(this.map.get("tzjh")+"")?"0":this.map.get("tzjh")+"").setScale(1, RoundingMode.UP)+"";
     String temp = new BigDecimal(trimpro).subtract(new BigDecimal(jnjhzh))+"";
     if("0".equals(temp)) {
     temp = "";
     }
     head = ExportUtil.getCzzscaList(jnjhzh, trimpro, temp);
     Map dounit = new HashMap();
     dounit.put("dwlx", 0);
     dounit.put("user_type", 1);
      List<Map> d_executeunit = unitDao.selectByPrimaryKey(dounit);
      Map zrbm = new HashMap();
      zrbm.put("dwlx", 1);
      zrbm.put("user_type", 1);
      List<Map> d_zrbm = unitDao.selectByPrimaryKey(zrbm);
      List<Map> zmtype = nd_caController.findProType("2-3-4");
     for (Map map: this.list) {
       List<String> row = new ArrayList<String>();
       for (int i = 0; i < key_columns.length; i++) {
       System.out.print(map.get(key_columns[i])+",");
       Object Otzjh = map.get("tzjh")!=null?map.get("tzjh"):0;
       Object Ojnjh = map.get("jnjh")!=null?map.get("jnjh"):0;
       BigDecimal tzjh = null;
       BigDecimal jnjh = null;
       if ("tzjh".equals(key_columns[i])||"jnjh".equals(key_columns[i])||"d_lnorde".equals(key_columns[i])) {
        if(Otzjh instanceof BigDecimal) {
          tzjh = (BigDecimal)Otzjh;
         }else {
     tzjh = new BigDecimal(Otzjh+"");
     }
         if(Ojnjh instanceof BigDecimal) {
          jnjh = (BigDecimal)Ojnjh;
         }else {
          jnjh = new BigDecimal(Ojnjh+"");
     }
         
       }
       if ("d_lnorde".equals(key_columns[i])) {
        if(map.get("flag")!=null&&"2".equals((map.get("flag")+""))) {
        row.add("");
        }else {
        row.add(tzjh.subtract(jnjh).setScale(1, RoundingMode.UP)+""); //不為整數則四舍五入
     }
   }else if ("xh".equals(key_columns[i])&&map.get("xh")!=null) {
        if(map.get("xh").toString().indexOf("、")>-1) {
        row.add(map.get("xh").toString().replace("、", "").trim());
        }else {
        row.add(map.get("xh")+""); //不為整數則四舍五入
     }
   }else if("tzjh".equals(key_columns[i])&&map.get("tzjh")!=null) { 
   if(ExportUtil.isNumeric(tzjh+"")) { //判斷相減是否為整數
    row.add(tzjh+"");
      }else {
       String stzjh = tzjh.setScale(1, RoundingMode.UP)+"";
       row.add("0".equals(stzjh.charAt(stzjh.indexOf(".")+1)+"")?stzjh.replace(".0", ""):stzjh);//不為整數則四舍五入
   }
   }else if("d_estimate".equals(key_columns[i])&&map.get("d_estimate")!=null) { 
   if("0".equals(map.get("d_estimate")+"")) {
    row.add("");
   }else {
    row.add(map.get("d_estimate")+"");
   }
   }else if("d_number".equals(key_columns[i])&&map.get("d_number")!=null) { 
   if("0".equals(map.get("d_number")+"")) {
    row.add("");
   }else {
    row.add(map.get("d_number")+"");
   }
   }else if("jnjh".equals(key_columns[i])&&map.get("jnjh")!=null) { 
   if(ExportUtil.isNumeric(jnjh+"")) { //判斷相減是否為整數
    row.add(jnjh+"");
      }else {
       String sjnjh = jnjh.setScale(1, RoundingMode.UP)+"";
       row.add("0".equals(sjnjh.charAt(sjnjh.indexOf(".")+1)+"")?sjnjh.replace(".0", ""):sjnjh); //不為整數則四舍五入
   }
   }else if("d_pro_type".equals(key_columns[i])&&map.get("d_pro_type")!=null) { 
   for (Map m : zmtype) {
    if((map.get("d_pro_type")+"").equals(m.get("TYPE_ID")+"")){
    row.add(m.get("NUM")+"");
    break;
    }
   }
       }else if("d_depart".equals(key_columns[i])&&map.get("d_depart")!=null) { 
        String d_depart = map.get("d_depart")+"";
        String depart = "";
        for (Map m : d_zrbm) {
        if((d_depart).indexOf(",")>-1) {
         for (String string : d_depart.split(",")) {
         if((string).equals(m.get("ID")+"")) {
          depart += ","+m.get("UNITNAME")+"";
          break;
           }
    }
        }else {
         if((d_depart).equals(m.get("ID")+"")) {
         depart = ","+m.get("UNITNAME")+"";
         break;
         }
        }
   }
        if (StringUtils.isNotBlank(depart)) {
        depart = depart.substring(1, depart.length()).replace(",", "\r ");
        row.add(depart);
   }else {
    row.add("");
   }
   }else if("d_executeunit".equals(key_columns[i])&&map.get("d_executeunit")!=null) { 
   boolean flag;
        for (Map m : d_executeunit) {
        flag = false;
        String executeunit = map.get("d_executeunit")+"";
        if((executeunit).indexOf(",")>-1) {
         for (String string : executeunit.split(",")) {
         if((string).equals(m.get("ID")+"")) {
          row.add((m.get("UNITNAME")+"").trim());
           flag = true;
           break;
           }
    }
         if (flag) {
         break;
    }
         
        }else {
         if((executeunit).equals(m.get("ID")+"")) {
         row.add((m.get("UNITNAME")+"").trim());
         break;
         }
        }
   }
       }else {
        if(map.get(key_columns[i])==null) {
        row.add("");
        }else {
        row.add((map.get(key_columns[i])+"").trim());
   }
   }
    }
       content.add(row);
  }
     head.addAll(content);
     int[] colWidths = new int[] { 600, 3000, 500, 500, 800, 800 ,800,3000,800,1500}; 
  XWPFDocument document = ExportUtil.exportWord(title,value_columns, head,colWidths,1,7);
  OutputStream out = response.getOutputStream(); 
     document.write(out);
     out.close();
     rm.setCode("1");
  rm.setMsg("導出成功");
 } catch (Exception e) {
  e.printStackTrace();
  rm.setCode("0");
  rm.setMsg("導出失敗,請刷新重試。");
 }
 return rm;
 }

四、工具類代碼

 /**
 * 
 * @Date 2018年7月19日 上午11:19:04
 * @Description 導出word 
 * @Fcunction exportWord
 * @param title
 * @param value_columns
 * @param list
 * @return XWPFDocument
 *
 */
 public static XWPFDocument exportWord(String title,String[] value_columns, List<List<String>> list,int[] colWidths,int one,int two) {
 XWPFDocument doc= new XWPFDocument();
 
 CTDocument1 document = doc.getDocument(); 
   CTBody body = document.getBody(); 
   if(!body.isSetSectPr()){ 
     body.addNewSectPr(); 
   } 
   CTSectPr section = body.getSectPr(); 
 
   if(!section.isSetPgSz()){ 
     section.addNewPgSz(); 
   } 
   CTPageSz pageSize = section.getPgSz(); 
   pageSize.setW(BigInteger.valueOf(15840));
   pageSize.setH(BigInteger.valueOf(12240));
   pageSize.setOrient(STPageOrientation.LANDSCAPE);
 
 //添加標題
   XWPFParagraph titleParagraph = doc.createParagraph();
   
   //設置段落居中
   titleParagraph.setAlignment(ParagraphAlignment.CENTER);
 
   XWPFRun titleParagraphRun = titleParagraph.createRun();
   titleParagraphRun.setText(title);
   titleParagraphRun.setColor("000000");
   titleParagraphRun.setFontSize(20);
 
   //表格
   XWPFTable ComTable = doc.createTable();
   
   //設置指定寬度
   CTTbl ttbl = ComTable.getCTTbl(); 
   CTTblGrid tblGrid = ttbl.addNewTblGrid();
   for (int i : colWidths) {
   CTTblGridCol gridCol = tblGrid.addNewGridCol(); 
   gridCol.setW(new BigInteger(i+"")); 
 }
   
   //表頭
   XWPFTableRow rowHead = ComTable.getRow(0);
   XWPFParagraph cellParagraph = rowHead.getCell(0).getParagraphs().get(0);
   cellParagraph.setAlignment(ParagraphAlignment.CENTER); //設置表頭單元格居中
   XWPFRun cellParagraphRun = cellParagraph.createRun();
 cellParagraphRun.setFontSize(10); //設置表頭單元格字號
 cellParagraphRun.setBold(true); //設置表頭單元格加粗
 cellParagraphRun.setText(value_columns[0]);
   for (int i = 1; i < value_columns.length; i++) {
   if(value_columns[i].indexOf("增減")>-1) {
    cellParagraph = rowHead.addNewTableCell().getParagraphs().get(0);
    cellParagraph.setAlignment(ParagraphAlignment.CENTER); //設置表頭單元格居中
    cellParagraphRun = cellParagraph.createRun();
  cellParagraphRun.setFontSize(10); //設置表頭單元格居中
  cellParagraphRun.setBold(true);
  cellParagraphRun.setText("增減(+ / -)");
  }else {
  cellParagraph = rowHead.addNewTableCell().getParagraphs().get(0);
    cellParagraph.setAlignment(ParagraphAlignment.CENTER); //設置表頭單元格居中
    cellParagraphRun = cellParagraph.createRun();
  cellParagraphRun.setFontSize(10); //設置表頭單元格居中
  cellParagraphRun.setBold(true); //設置表頭單元格加粗
  cellParagraphRun.setText(value_columns[i]);
  }
 }
   int rows = list.size();
   //表格內容
   for (int i = 0; i < rows; i++) {
   XWPFTableRow rowsContent = ComTable.createRow();
   for (int j = 0; j < list.get(i).size(); j++) {
    XWPFParagraph cellParagraphC = rowsContent.getCell(j).getParagraphs().get(0);
    if(j!=one&&j!=two) {
    cellParagraphC.setAlignment(ParagraphAlignment.CENTER); //設置表格內容居中
    }
    XWPFRun cellParagraphRunC = cellParagraphC.createRun();
    cellParagraphRunC.setFontSize(10); //設置表格內容字號
    cellParagraphRunC.setText(list.get(i).get(j)+""); //單元格段落加載內容
  }
   }
   if(rows==0) {
   for (int i = 0; i < value_columns.length; i++) {
    XWPFTableCell cell = ComTable.getRow(0).getCell(i);
       cell.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER); //垂直居中
  }
   }else {
     //設置居中
     for (int i = 0; i <= rows; i++) {
       for (int j = 0; j < list.get(0).size(); j++) {
         XWPFTableCell cell = ComTable.getRow(i).getCell(j);
         cell.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER); //垂直居中
       }
     }
 }
 return doc;
 }
 
 /**
 * 
 * @Date 2018年7月19日 上午11:19:21
 * @Description 判斷是否是整數 
 * @Fcunction isNumeric
 * @param str
 * @return boolean
 *
 */
 public static boolean isNumeric(String str) {
 if(str.indexOf(".")>0) {
  return false;
 }
 return true;
 }
 
 /**
 * 
 * @Date 2018年7月19日 上午11:44:48
 * @Description 正式計劃草案獲取前兩行 
 * @Fcunction getCzzscaList
 * @param jnjhzh
 * @param trimpro
 * @param temp
 * @return List<List<String>>
 *
 */
 public static List<List<String>> getCzzscaList(String jnjhzh,String trimpro,String temp) {
 List<List<String>> list = new ArrayList<List<String>>();
 List<String> l1 = new ArrayList<String>(); //固定第一行
   l1.add(""); 
   l1.add("年度總計"); 
   l1.add(""); 
   l1.add(""); 
   l1.add(""); 
   l1.add(""); 
   l1.add(jnjhzh); 
   l1.add(""); 
   l1.add(""); 
   l1.add(""); 
   list.add(l1);
   List<String> l2 = new ArrayList<String>(); //固定第二行
   l2.add("");
   l2.add("搜索總計");
   l2.add("");
   l2.add("");
   l2.add("");
   l2.add("");
   l2.add("");
//   l2.add(trimpro+"\r100%");
   l2.add("");
   l2.add("");
   l2.add("");
   list.add(l2);
 return list;
 }

五、詳解:

1.設置紙張大小

(1)創建完XWPFDocument后,默認為A4紙張,如需調整紙張大小,這里我是要用A3大小使用如下代碼

XWPFDocument doc= new XWPFDocument();
CTDocument1 document = doc.getDocument(); 
CTBody body = document.getBody(); 
if(!body.isSetSectPr()){ 
  body.addNewSectPr(); 
} 
CTSectPr section = body.getSectPr(); 
 
if(!section.isSetPgSz()){ 
  section.addNewPgSz(); 
} 
CTPageSz pageSize = section.getPgSz(); 
pageSize.setW(BigInteger.valueOf(15840));
pageSize.setH(BigInteger.valueOf(12240));
pageSize.setOrient(STPageOrientation.LANDSCAPE);

(2)默認A4紙張大小的話只用XWPFDocument

XWPFDocument doc= new XWPFDocument();

(3)使用CTPageSz類需要導入ooxml-schemas的jar包(所有需要的jar包maven依賴在底部)

2.單元格列寬度

(1)每一列寬度相等自適應,不需單獨設置每一列寬度的話使用如下代碼

//表格
XWPFTable ComTable = doc.createTable();
//表格自適應寬度
CTTblWidth comTableWidth = ComTable.getCTTbl().addNewTblPr().addNewTblW();
comTableWidth.setType(STTblWidth.DXA);
comTableWidth.setW(BigInteger.valueOf(9072));

(2)單獨設置每列寬度

//表格
XWPFTable ComTable = doc.createTable();   
//設置指定寬度
CTTbl ttbl = ComTable.getCTTbl(); 
CTTblGrid tblGrid = ttbl.addNewTblGrid();
int[] colWidths = new int[] { 600, 3000, 500, 500, 800, 800 ,800,3000,800,1500}; 
for (int i : colWidths) {
  CTTblGridCol gridCol = tblGrid.addNewGridCol(); 
  gridCol.setW(new BigInteger(i+"")); 
}

(3)使用CTTblGrid類需要導入poi-ooxml-schemas的jar包(所有需要的jar包maven依賴在底部)

3.單元格內字體樣式

(1)不需要設置單元格字體

for (int i = 0; i < rows; i++) {
  XWPFTableRow rowsContent = ComTable.createRow();
  for (int j = 0; j < list.get(i).size(); j++) {  
    rowsContent.getCell(j).setText(list.get(i).get(j)+""); //用單元格加載內容
  }
}

(2)設置單元格內字體字號、是否加粗

for (int i = 0; i < rows; i++) {
  XWPFTableRow rowsContent = ComTable.createRow();
  for (int j = 0; j < list.get(i).size(); j++) {
    XWPFParagraph cellParagraphC = rowsContent.getCell(j).getParagraphs().get(0);
    if(j!=1&&j!=7) {
      cellParagraphC.setAlignment(ParagraphAlignment.CENTER); //設置表格內容居中
    }
    XWPFRun cellParagraphRunC = cellParagraphC.createRun();
    cellParagraphRunC.setFontSize(10); //設置表格內容字號
    cellParagraphRun.setBold(true); //設置表頭單元格加粗
    cellParagraphRunC.setText(list.get(i).get(j)+""); //單元格段落加載內容
  }
}

4.單元格居中(水平居中、垂直居中)

(1)使用單元格加載內容

for (int i = 0; i < value_columns.length; i++) {
  XWPFTableCell cell = ComTable.getRow(0).getCell(i);
  cell.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER); //垂直居中
  CTTc cttc = cell.getCTTc();
  CTP ctp = cttc.getPList().get(0);
  CTPPr ctppr = ctp.getPPr();
  if (ctppr == null) {
    ctppr = ctp.addNewPPr();
  }
  CTJc ctjc = ctppr.getJc();
  if (ctjc == null) {
    ctjc = ctppr.addNewJc();
  }
  ctjc.setVal(STJc.CENTER); //水平居中
}

(2)使用單元格的段落加載內容,只用調用垂直居中的方法

for (int i = 0; i < value_columns.length; i++) {
  XWPFTableCell cell = ComTable.getRow(0).getCell(i);
  cell.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER); //垂直居中
}

水平居中在3-(2)里調用了段落的方法居中過了

cellParagraphC.setAlignment(ParagraphAlignment.CENTER);

5.單元格合并

(1)跨列合并單元格

public static void mergeCellsHorizontal(XWPFTable table, int row, int fromCell, int toCell) {
 for (int cellIndex = fromCell; cellIndex <= toCell; cellIndex++) {
  XWPFTableCell cell = table.getRow(row).getCell(cellIndex);
  if ( cellIndex == fromCell ) {  
  cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.RESTART);
  } else {
  cell.getCTTc().addNewTcPr().addNewHMerge().setVal(STMerge.CONTINUE);
  }
 }
 }

(2)跨行合并單元格

public static void mergeCellsVertically(XWPFTable table, int col, int fromRow, int toRow) {
 for (int rowIndex = fromRow; rowIndex <= toRow; rowIndex++) {
  XWPFTableCell cell = table.getRow(rowIndex).getCell(col);
  if ( rowIndex == fromRow ) {
  cell.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.RESTART);
  } else {
  cell.getCTTc().addNewTcPr().addNewVMerge().setVal(STMerge.CONTINUE);
  }
 }
 }

6.單元格內換行,單元格內使用\r換行沒用,可以用addBreak方法

 for (int i = 0; i < list_vPostdutyNorm_parm.size(); i++) {
  row = ComTable.createRow();
  index++;
  for (int j = 0; j < list_vPostdutyNorm_parm.get(i).size(); j++) {
  if (j == 3 || j == 4) {
   cellParagraph.setAlignment(ParagraphAlignment.LEFT); //設置表頭單元格居中
  } else {
   cellParagraph.setAlignment(ParagraphAlignment.CENTER); //設置表頭單元格居中
  }
  String content = list_vPostdutyNorm_parm.get(i).get(j);
  cellParagraph = row.getCell(j).getParagraphs().get(0);
  cellParagraphRun = cellParagraph.createRun();
  cellParagraphRun.setFontSize(10); //設置表頭單元格字號
  cellParagraphRun.setBold(false); //設置表頭單元格加粗
  if (content.indexOf("\r") > -1) {
   String[] text = content.split("\r");
   for (int k = 0; k < text.length; k++) {
   if (k == 0) {
    cellParagraphRun.setText(text[k]);
   }else {
    cellParagraphRun.addBreak();
    cellParagraphRun.setText(text[k]);
   }
   }
  }else {
   cellParagraphRun.setText(content);
  }
  }
 }

六、使用到的Maven依賴

<dependency>
  <groupId>org.apache.xmlbeans</groupId>
  <artifactId>xmlbeans</artifactId>
  <version>2.6.0</version>
</dependency>
<dependency>
  <groupId>org.apache.poi</groupId>
  <artifactId>poi-ooxml</artifactId>
  <version>3.9</version>
</dependency>
<dependency>
  <groupId>org.apache.poi</groupId>
  <artifactId>ooxml-schemas</artifactId>
  <version>1.1</version>
</dependency>
<dependency>
  <groupId>org.apache.poi</groupId>
  <artifactId>poi-ooxml-schemas</artifactId>
  <version>3.16</version>
</dependency>

以上這篇poi導出word表格的操作講解就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持億速云。

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

汉川市| 大庆市| 二连浩特市| 绩溪县| 郯城县| 伽师县| 文成县| 高清| 金秀| 潼南县| 黑龙江省| 台江县| 泰顺县| 凤翔县| 法库县| 汕头市| 陇西县| 庆安县| 惠东县| 突泉县| 德安县| 浦北县| 大同市| 舒兰市| 二手房| 安义县| 镶黄旗| 石泉县| 安岳县| 瑞昌市| 根河市| 静乐县| 惠来县| 亳州市| 本溪| 阳信县| 临城县| 曲松县| 沂南县| 沁阳市| 浑源县|