Java - Use jxl NumberFormats or Jxcell setCustomFormat to set number format

當我們產出報表時,如果金額需要產生三位一撇的格式,並且當數字小於零時會自動標記為

紅色,jxl可以使用NumberFormats class來處理,若是JXCell可以使用CellFormat的

setCustomFormat method來自訂格式。

jxl 範例程式碼如下:
Workbook sWorkbook = Workbook.getWorkbook(new File("D:\\template.xls"));
WritableWorkbook wWorkbook = Workbook.createWorkbook(new File("D:\\result.xls"), sWorkbook);
WritableSheet sheet = wWorkbook.getSheet(0);
   
WritableCellFormat nf1 = new WritableCellFormat(NumberFormats.FORMAT1);
sheet.addCell(new Number(0, 5, 12345, nf1));
sheet.addCell(new Number(1, 5, -12345, nf1));
      
WritableCellFormat nf2 = new WritableCellFormat(NumberFormats.FORMAT2);
sheet.addCell(new Number(0, 6, 12345, nf2));
sheet.addCell(new Number(1, 6, -12345, nf2));
   
WritableCellFormat nf3 = new WritableCellFormat(NumberFormats.FORMAT3);
sheet.addCell(new Number(0, 7, 12345, nf3));
sheet.addCell(new Number(1, 7, -12345, nf3));
      
WritableCellFormat nf4 = new WritableCellFormat(NumberFormats.FORMAT4);
sheet.addCell(new Number(0, 8, 12345, nf4));
sheet.addCell(new Number(1, 8, -12345, nf4));

wWorkbook.write();
wWorkbook.close();


row 6為FORMAT1格式,相當於"#,##0;(#,##0)"

row 7為FORMAT2格式,相當於FORMAT1,但針對負數會另外區別

row 8為FORMAT3格式,相當於"#,##0.00;(#,##0.00)"

row 9為FORMAT4格式,相當於FORMAT3,但針對負數會另外區別


JXCell 範例程式如下:
View m_view=new View();  
m_view.read("D:\\template.xls");
ConditionFormat condfmt= m_view.CreateConditionFormat();
CellFormat cf=condfmt.getCellFormat();

cf.setCustomFormat("#,###0.00;[red]-#,###0.00;0.00");
m_view.setSelection(5, 0, 5, 1);
m_view.setCellFormat(cf);

cf.setCustomFormat("#,###;[red]-#,###;0");
m_view.setSelection(6, 0, 6, 1);
m_view.setCellFormat(cf);

m_view.setNumber(0, 5, 0, 12345);
m_view.setNumber(0, 5, 1, -12345);
m_view.setNumber(0, 6, 0, 12345);
m_view.setNumber(0, 6, 1, -12345);
m_view.write("D:\\result2.xls");



JXCell setCustomDormat內設定的字串,語法相當於在Excel使用儲存格的自訂格式!

請注意正數與負數及0用分號隔開,0的部分要訂,否則當此儲存格寫入0時會變成沒有值!


但別忘了[red]要寫英文字才有效XD

留言