การสร้าง Cell ใน Excel โดยใช้ Java POI
เราได้สร้าง sheet ใน excel กันไปแล้ว ต่อไปมาดูวิธีการสร้าง cell กันบ้าง ซึ่งก็เป็นวิธีการง่าย ๆ ในการสร้าง Cell ใน Excel โดยใช้ Java POI เราลองมาดูโค้ดที่ใช้ในการสร้าง Cell กันก่อนครับ ตามด้านล่าง
package info.doesystem.tutorial.poi;
import java.io.FileOutputStream;
import java.util.Calendar;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class NewCell {
public static void main(String[] args) {
try (
Workbook wb = new XSSFWorkbook();
FileOutputStream fileOut = new FileOutputStream("D://Blog/Temp File/workbook.xlsx")
){
// create sheet
Sheet sheet = wb.createSheet("new sheet");
// create row
Row row = sheet.createRow(0);
// create cell
Cell cell = row.createCell(0);
// set value to cell
cell.setCellValue(1);
// other example
row.createCell(1).setCellValue("Test");
row.createCell(2).setCellValue(Calendar.getInstance());
row.createCell(3).setCellValue(Calendar.getInstance().getTime());
CreationHelper createHelper = wb.getCreationHelper();
row.createCell(4).setCellValue(createHelper.createRichTextString("This is a string"));
wb.write(fileOut);
System.out.println("SUCCESS");
} catch (Exception ex) {
System.out.println("Exception " + ex);
}
}
}
จากโค้ดจะเห็นว่าเราต้องทำการสร้าง Sheet จากนั้นก็สร้าง Row จากนั้นในแต่ละ Row เราถึงจะสร้าง Cell เมื่อต้องการเซตค่าให้กับแต่ละ Cell ก็เพียงแค่เรียก setCellValue เพียงแค่นี้เราก็ได้ทำการเซตค่าให้กับแต่ละ Cell แล้ว
ไม่มีความคิดเห็น:
แสดงความคิดเห็น