生成Excel檔案並存儲到指定磁碟路徑下
阿新 • • 發佈:2019-01-02
描述: 這個方法呢, 是在專案中粘出來的,當然不能說是複製貼上就能用, 這裡面只需要部分內容就可以實現需要的功能.
藍色部分為需要匯入的包 , 紅色部分為主題內容,用來生成Excel檔案和部分格式設定. Excel當成是一個表格, 往裡面插入資料需要 每一行每一列的插入, 所以 用兩個for迴圈插入資料(見黃色部分程式碼) .
然後呢, 是已經插入資料完 要把檔案儲存在本地磁碟某個路徑下面, 那麼 就需要判斷該路徑是否存在, 最後將檔案以流的形式傳輸到指定目錄下 生成Excel還是比較簡單的 . 如果要更多瞭解 搜尋 POI 即可, 我僅是在工作時用一下啦 ,然後作一個分享和記錄,方便以後取用. 若有不足之處 ,請指出,謝謝
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;import org.apache.poi.hssf.usermodel.HSSFWorkbook;
/**
* 生成excel* @throws IOException
*/
public static void createExcel( String list,......) throws IOException{
//建立HSSFWorkbook物件(excel的文件物件)
HSSFWorkbook wb = new HSSFWorkbook();
// 建立新的sheet物件(excel的表單)
HSSFSheet sheet = wb.createSheet("sheet1");
// 在sheet裡建立第一行,引數為行索引(excel的行),可以是0~65535之間的任何一個
HSSFRow row0 = sheet.createRow(0);
// 新增表頭
row0.createCell(0).setCellValue("測站名稱");
row0.createCell(1).setCellValue("測站程式碼");
row0.createCell(2).setCellValue("物件名稱");
row0.createCell(3).setCellValue("斷面名稱");
row0.createCell(4).setCellValue("斷面級別");
row0.createCell(5).setCellValue("檢測時間");
row0.createCell(6).setCellValue("水期程式碼");
for(int i = 0;i<wrwmclist.size();i++){
String wrwmc = wrwmclist.get(i);
row0.createCell(7+i).setCellValue(wrwmc);
if(i==wrwmclist.size()-1){
row0.createCell(7+i+1).setCellValue("備註");
}
}
//格式化數字
NumberFormat nf = NumberFormat.getInstance();
// 建立單元格(excel的單元格,引數為列索引,可以是0~255之間的任何一個
// 在sheet裡建立往下的行
for(int i= 0;i<datalist.size();i++){
DynaBean db = datalist.get(i);
HSSFRow row = sheet.createRow(i+1);
row.createCell(0).setCellValue(db.get("SSXZQ")!=null?db.get("SSXZQ").toString():"");
row.createCell(1).setCellValue(db.get("ORGID")!=null?db.get("ORGID").toString():"");
row.createCell(2).setCellValue(db.get("DXMC")!=null?db.get("DXMC").toString():"");
row.createCell(3).setCellValue(db.get("CDMC")!=null?db.get("CDMC").toString():"");
String jgjb = db.get("JGJB")!=null?db.get("JGJB").toString():"";
row.createCell(4).setCellValue(dmjbMap(jgjb));
row.createCell(5).setCellValue(db.get("CYSJ")!=null?db.get("CYSJ").toString():"");
row.createCell(6).setCellValue(db.get("SQDM")!=null?db.get("SQDM").toString():"");
for(int n = 0;n<fxxmdmlist.size();n++){
String wrwdm = fxxmdmlist.get(n);
String strnum = "0";
if(db.get(wrwdm)!=null){
strnum = subZeroAndDot(db.get(wrwdm).toString()) ;//去掉多餘的 0
strnum = new BigDecimal(strnum).toPlainString();//避免科學計數
strnum = nf.format(Double.parseDouble(strnum));//去掉 值為 0 的所有小數
}
row.createCell(7+n).setCellValue(strnum);
if(n==fxxmdmlist.size()-1){
row.createCell(7+n+1).setCellValue(db.get("BZ")!=null?db.get("BZ").toString():"");
}
}
}
//判斷是否存在目錄. 不存在則建立
isChartPathExist(filepath);
//輸出Excel檔案1
FileOutputStream output=new FileOutputStream(filepath+filename);
wb.write(output);//寫入磁碟
output.close();
}