Java如何在電子試算表中建立不同型別的單元格?

2019-10-16 22:27:41

在Java程式設計中,如何在電子試算表中建立不同型別的單元格?

注意:需要存取網址:http://poi.apache.org/download.html , 下載一個Apache POI軟體包。這裡下載最新版本:poi-bin-3.17-20170915.tar.gz解壓並將全部.jar檔案匯入 。

需要匯入全部包,如下圖所示 -

以下是使用Java在電子試算表中建立不同型別的單元格的程式。

package com.yiibai;

import java.io.File;
import java.io.FileOutputStream;

import java.util.Date;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class TypesOfCellsInExcel {
   public static void main(String[] args)throws Exception {

      //Creating a Workbook
      XSSFWorkbook workbook = new XSSFWorkbook();

      //Creating a Spread sheet
      XSSFSheet spreadsheet = workbook.createSheet("單元格型別");
      XSSFRow row = spreadsheet.createRow((short) 2);

      row.createCell(0).setCellValue("單元格型別");
      row.createCell(1).setCellValue("單元格值");
      row = spreadsheet.createRow((short) 3);

      row.createCell(0).setCellValue("set cell type BLANK");
      row.createCell(1);
      row = spreadsheet.createRow((short) 4);

      row.createCell(0).setCellValue("set cell type BOOLEAN");
      row.createCell(1).setCellValue(true);
      row = spreadsheet.createRow((short) 5);

      row.createCell(0).setCellValue("set cell type ERROR");
      row.createCell(1).setCellValue(XSSFCell.CELL_TYPE_ERROR );
      row = spreadsheet.createRow((short) 6);

      row.createCell(0).setCellValue("set cell type date");
      row.createCell(1).setCellValue(new Date());
      row = spreadsheet.createRow((short) 7);

      row.createCell(0).setCellValue("set cell type numeric" );
      row.createCell(1).setCellValue(20 );
      row = spreadsheet.createRow((short) 8);

      row.createCell(0).setCellValue("set cell type string");
      row.createCell(1).setCellValue("A String");

      FileOutputStream out = new FileOutputStream(new File("typesofcells.xlsx"));
      workbook.write(out);
      out.close();
      System.out.println("typesofcells.xlsx written successfully");
   }
}

執行上面範例程式碼,得到以下結果 -

typesofcells.xlsx written successfully

建立的Excel檔案內容,如下所示 -