จากโคดตัวอย่างเราจะสร้างไฟล์ .xlsx ดังนั้น ผู้เขียนจึงใช้ Package XSSF แต่หากใครจะสร้างไฟล์ .xls เฉยๆให้เรียกใช้ Package HSSF นะครับ
ตัวอย่างโคด
package com.java.poi.excel;
import java.io.FileOutputStream;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class NewLineExcel {
public static void main(String[] args) {
try {
// สร้าง object ของ excel
XSSFWorkbook wb = new XSSFWorkbook();
// สร้าง sheet
XSSFSheet spreadsheet = wb.createSheet("New Line Excel");
// สร้างแถวแรก การนับแถวเริ่มจาก 0,1,2....
XSSFRow row = spreadsheet.createRow(2);
XSSFCell cell = row.createCell(2);
cell.setCellValue("Use \n with word wrap on to create a new line");
// การขึ้นบรรทัดใหม่ให้ข้อความโดยการใช้ style โดยกำหนด wrap=true
XSSFCellStyle cs = wb.createCellStyle();
cs.setWrapText(true);
cell.setCellStyle(cs);
// เพิ่มความสูงของแถวประมาณสองเท่าของขนาดแถวปัจจุบัน
row.setHeightInPoints((2*spreadsheet.getDefaultRowHeightInPoints()));
// เพิ่มความกว้างของคอลัมน์ตามความกว้างของข้อความ
spreadsheet.autoSizeColumn(2);
// path ของไฟล์
FileOutputStream out = new FileOutputStream("C:\\poi\\NewLineExcel.xlsx");
wb.write(out);
wb.close();
out.close();
System.out.println("Excel created successfully");
} catch (Exception e) {
e.printStackTrace();
}
}
}
ไฟล์ที่ถูกสร้าง
ผลลัพธ์ที่ได้


0 comments:
Post a Comment