Đề Xuất 4/2023 # Đọc Ghi Excel File Sử Dụng Apache Poi # Top 12 Like | Beiqthatgioi.com

Đề Xuất 4/2023 # Đọc Ghi Excel File Sử Dụng Apache Poi # Top 12 Like

Cập nhật nội dung chi tiết về Đọc Ghi Excel File Sử Dụng Apache Poi mới nhất trên website Beiqthatgioi.com. Hy vọng thông tin trong bài viết sẽ đáp ứng được nhu cầu ngoài mong đợi của bạn, chúng tôi sẽ làm việc thường xuyên để cập nhật nội dung mới nhằm giúp bạn nhận được thông tin nhanh chóng và chính xác nhất.

Do vậy, trong bài viết này, mình đã giới thiệu về Apache POI là một thư viện mã nguồn mở cho phép chúng ta thao tác với các tập tin định dạng microsoft office. Trong bài viết này chúng ta sẽ cùng nhau tìm hiểu cách đọc và ghi excel file sử dụng Apache POI.

Maven denpendency

Để thao tác được với Excel file, chúng ta cần thêm các denpendency cần thiết.

Một số lưu ý khi sử dụng Apache POI

Bài viết này sẽ hướng dẫn các bạn cách đọc và ghi file excel sử dụng thư viện Apache POI. Tuy nhiên có một số lưu ý sau các bạn cần chú ý để có thể triển khai cho từng trường hợp của mình.

Tiền tố HSSF được đặt trước các tên class dùng để thao tác với các file định dạng Microsoft Excel 2003.

Tiền tố XSFF được đặt trước các tên class dùng để thao tác với các file định dạng Microsoft Excel 2007.

XSSFWorkbook và HSSFWorkbook là các class đại diện cho một excel workbook.

HSSFSheet và XSSFSheet là các class đại diện cho một excel WorkSheet.

Row đại diện cho một dòng.

Cell đại diện cho một ô trong một hàng xác định.

Trong bài hướng dẫn này, các bạn sẽ được hướng dẫn cách đọc ghi file excel Microsoft Excel 2007 có đôi là xlsx, có nghĩa là chúng ta sẽ sử dụng các class có tiền tố là XSFF để đọc file exel.

Ghi excel file

Để ghi một excel file cần qua những bước cơ bản sau:

Tạo workbook.

Tạo một sheet trong workbook.

Tạo một dòng trong sheet.

Thêm một cột trong sheet.

import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import java.io.File; import java.io.FileOutputStream; import java.util.Map; import java.util.Set; import java.util.TreeMap; public class Main { public static void main(String[] args) { XSSFWorkbook workbook = new XSSFWorkbook(); XSSFSheet sheet = workbook.createSheet("student Details"); data.put("1", new Object[]{"ID", "NAME", "LASTNAME"}); data.put("2", new Object[]{1, "Pankaj", "Kumar"}); data.put("3", new Object[]{2, "Prakashni", "Yadav"}); data.put("4", new Object[]{3, "Ayan", "Mondal"}); data.put("5", new Object[]{4, "Virat", "kohli"}); int rownum = 0; for (String key : keyset) { Row row = sheet.createRow(rownum++); Object[] objArr = data.get(key); int cellnum = 0; for (Object obj : objArr) { Cell cell = row.createCell(cellnum++); if (obj instanceof String) cell.setCellValue((String) obj); else if (obj instanceof Integer) cell.setCellValue((Integer) obj); } } try { FileOutputStream out = new FileOutputStream(new File("gfgcontribute.xlsx")); workbook.write(out); out.close(); System.out.println("gfgcontribute.xlsx written successfully on disk."); } catch (Exception e) { e.printStackTrace(); } } }

Đọc file excel

Để đọc một excel file chúng ta cũng có các bước sau:

Khởi tạo một workbook instance từ excel file.

Lấy sheet từ workbook.

Đọc từng dòng, mỗi dòng lấy giá trị từ từng cột.

import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import java.io.File; import java.io.FileInputStream; import java.util.Iterator; public class Main { public static void main(String[] args) { try { FileInputStream file = new FileInputStream(new File("gfgcontribute.xlsx")); XSSFWorkbook workbook = new XSSFWorkbook(file); XSSFSheet sheet = workbook.getSheetAt(0); while (rowIterator.hasNext()) { Row row = rowIterator.next(); while (cellIterator.hasNext()) { Cell cell = cellIterator.next(); switch (cell.getCellType()) { case Cell.CELL_TYPE_NUMERIC: System.out.print(cell.getNumericCellValue() + "t"); break; case Cell.CELL_TYPE_STRING: System.out.print(cell.getStringCellValue() + "t"); break; } } System.out.println(""); } file.close(); } catch (Exception e) { e.printStackTrace(); } } }

Output:

IDtNAMEtLASTNAMEt1.0tPankajtKumart2.0tPrakashnitYadavt3.0tAyantMondalt4.0tVirattkohlit

Note: Nếu bạn muốn đọc một file tại một đường dẫn khác, thì bạn chỉ việc thay

FileInputStream file = new FileInputStream(new File("gfgcontribute.xlsx"));

thành đường dẫn bạn mong muốn.

Thêm dữ liệu vào sheet

Nếu bạn đã có một excel sẵn và muốn ghi thêm dự liệu vào đó, thì chỉ cần lấy sheet đó ra từ workbook, đi đến dòng cuối cùng và bắt đầu ghi thêm dữ liệu vào.

private static final String FILE_NAME = "C:\Users\pankaj\Desktop\projectOutput\blo.xlsx"; public static void write() throws IOException, InvalidFormatException { InputStream inp = new FileInputStream(FILE_NAME); Workbook wb = WorkbookFactory.create(inp); Sheet sheet = wb.getSheetAt(0); int num = sheet.getLastRowNum(); Row row = sheet.createRow(++num); row.createCell(0).setCellValue("xyz"); ..... .. FileOutputStream fileOut = new FileOutputStream(FILE_NAME); wb.write(fileOut); fileOut.close(); }

Nguồn tham khảo

https://www.geeksforgeeks.org/reading-writing-data-excel-file-using-apache-poi/

Đọc Ghi File Excel Trong Java Sử Dụng Apache Poi

1- Apache POI là gì?

Apache POI là một thư viện mã nguồn mở Java, được cung cấp bởi Apache, nó là một thư viện đầy sức mạnh giúp bạn làm việc với các tài liệu của Microsoft như Word, Excel, Power point, Visio,…

POI là viết tắt của“Poor Obfuscation Implementation”. Các định dạng file của Microsoft được giấu kín. Những kỹ sư của Apache phải cố gắng để tìm hiểu nó, và họ thấy rằng Microsoft đã tạo ra các định dạng phức tạp một cách không cần thiết. Và cái tên thư viện bắt nguồn từ sự hài ước.

Poor Obfuscation Implementation: Sự thực hiện cái nghèo nàn ngu muội. (Tạm dịch là vậy).

Trong tài liệu này tôi hướng dẫn các bạn sử dụng Apache POI để làm việc với Excel.

Apache POI hỗ trợ bạn làm việc với các định dạng của Microsoft, các class của nó thường có tiếp đầu ngữ HSSF, XSSF, HPSF, … Nhìn vào tiếp đầu ngữ của một class bạn có thể biết được class đó hỗ trợ loại định dạng nào.

Chẳng hạn để làm việc với các định dạng Excel (XLS) bạn cần các class:

HSSFWorkbook

HSSFSheet

HSSFCellStyle

HSSFDataFormat

HSSFFont

Apache POI cung cấp cho bạn các interfaceWorkbook,Sheet,Row,Cell,… và các class thể hiện (implementation) tương ứng là HSSFWorkbook, HSSFSheet, HSSFRow, HSSFCell,…

Nếu project của bạn sử dụng Maven, bạn chỉ cần khai báo thư viện một cách đơn giản trong chúng tôi :

Nếu bạn không sử dụng Maven bạn có thể download thư viện Apache POI tại:

Download về và giải nén, để làm việc với Excel bạn cần ít nhất 3 file jar:

poi-**.jar

lib/commons-codec-**.jar

lib/commons-collections4-**.jar

Trong tài liệu này, tôi tạo một Project Maven đơn giản có tên ApachePOIExcel

Group ID: org.o7planning

Artifact ID: ApachePOIExcel

Microsoft Office các phiên bản trước đây (97-2003) các file excel có định dạng XLS và các phiên bản mới thường sử dụng định dạng XSLX. Để thao tác với các file XSL bạn cần sử dụng các class có tiếp đầu ngữ HSSF. Còn đối với các file định dạng XSLX cần sử dụng các class có tiếp đầu ngữ XSSF.

Chú ý: Trong tài liệu này tôi đang sử dụng Apache POI 3.15, API có nhiều thay đổi so với phiên bản cũ hơn. Có nhiều phương thức sẽ bị loại bỏ trong phiên bản tương lai (Apache POI 4.x). POI đang hướng tới sử dụng Enum thay thế cho các hằng số trong API của nó.

7- Cập nhập file Excel có sẵn

Trong ví dụ này, tôi đọc file excel chúng tôi và cập nhập các giá trị cho cột Salary tăng lên 2 lần.

Kết quả sau khi cập nhập:

Nếu bạn có kiến thức về Excel, sẽ không khó để bạn thiết lập một công thức. Với Apache POI bạn có thể tạo một Cell có kiểu CellType.FORMULA, giá trị của nó được tính dựa trên một công thức.

SUM

Ví dụ: Tính tổng các ô trên cùng cột “C” từ dòng thứ 2 tới dòng thứ 4:

cell = row.createCell(rowIndex, CellType.FORMULA); cell.setCellFormula("SUM(C2:C4)");

Công thức từ các ô riêng lẻ:

cell = row.createCell(rowIndex, CellType.FORMULA); cell.setCellFormula("0.1*C2*D3");

Với một cell có kiểu FORMULA bạn có thể in ra công thức của nó và sử dụng FormulaEvaluator để tính toán giá trị của ô cho bởi công thức đó.

String formula = cell.getCellFormula(); FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator(); CellValue cellValue = evaluator.evaluate(cell); double value = cellValue.getNumberValue(); String value = cellValue.getStringValue(); boolean value = cellValue.getBooleanValue();

Đọc Ghi File Ms Word Bằng Java Với Apache Poi

Đọc ghi file MS Word bằng Java với Apache POI

Apache POI là một thư viện mã nguồn mở cung cấp bởi apache được sử dụng để xử lý các file office như word, excel, powerpoint…

XWPFDocument:Được sử dụng để đọc ghi các file MS-Word với định dạng .docx (đọc, lưu file, thêm đoạn văn bản…)

XWPFParagraph: Được dùng để tạo đoạn paragraph trong tài liệu word. (Tùy chỉnh căn lề, border)

XWPFRun: Được sử dụng thể thêm text vào paragraph (Tùy chỉnh font, size…)

XWPFTable: Được dùng để thêm mới bảng vào file (Thêm cột, thêm dòng, cài đặt chiều rộng cho cột)

XWPFWordExtractor: Đây là class cơ bản được dùng để lấy text đơn giản từ tài liệu word (lấy tất cả text bên trong file word)

Thư viện sử dụng:

Ví dụ ghi file MS Word:

package stackjava.com.apachepoi.word.demo; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.apache.poi.xwpf.usermodel.XWPFParagraph; import org.apache.poi.xwpf.usermodel.XWPFRun; public class DemoWrite { public static void main(String[] args) throws IOException { XWPFDocument document = new XWPFDocument(); XWPFParagraph paragraph1 = document.createParagraph(); XWPFRun run = paragraph1.createRun(); run.setText("Paragraph 1: stackjava.com"); XWPFParagraph paragraph2 = document.createParagraph(); run = paragraph2.createRun(); run.setText("Paragraph 2: demo read/write file MS-Word"); FileOutputStream out = new FileOutputStream(new File("demo-apache-apoi-word.docx")); document.write(out); out.close(); document.close(); System.out.println("successully"); } }

Kết quả:

package stackjava.com.apachepoi.word.demo; import java.io.FileInputStream; import java.util.List; import org.apache.poi.openxml4j.opc.OPCPackage; import org.apache.poi.xwpf.extractor.XWPFWordExtractor; import org.apache.poi.xwpf.usermodel.XWPFDocument; import org.apache.poi.xwpf.usermodel.XWPFParagraph; public class DemoRead { public static void main(String[] args) { try { FileInputStream fis = new FileInputStream("demo-apache-apoi-word.docx"); XWPFDocument document = new XWPFDocument(OPCPackage.open(fis)); for (XWPFParagraph paragraph : paragraphList) { System.out.println(paragraph.getText()); } System.out.println("=============================="); System.out.println("Read file using XWPFWordExtractor "); XWPFWordExtractor wordExtractor = new XWPFWordExtractor(document); System.out.println(wordExtractor.getText()); wordExtractor.close(); document.close(); } catch (Exception ex) { ex.printStackTrace(); } } }

Kết quả:

Paragraph 1: stackjava.com Paragraph 2: demo read/write file MS-Word ============================== Read file using XWPFWordExtractor Paragraph 1: stackjava.com Paragraph 2: demo read/write file MS-Word

Okay, Done!

References:

https://poi.apache.org/document/

Đọc Ghi File Excel Trong Java Với Jxl

Tạo và ghi file Excel với Jxl

Bước 1: Tạo đối tượng WritableWorkbook “trỏ” đến file của bạn. Lưu ý là nếu file của bạn đã tồn tại thì nó sẽ bị xóa đi và tạo lại.

WritableWorkbook workbook = Workbook.createWorkbook(new File(fileName));

Bước 2: Tạo WritableSheet – sheet bạn cần ghi dữ liệu:

WritableSheet sheet = workbook.createSheet("name sheet", 0);

Lưu ý: trong hàm createSheet có 2 đối số, đối số thứ nhất là chuỗi tên sheet, đối số thứ 2 là một số nguyên chỉ vị trí của sheet, vị trí sheet bắt đầu bằng 0.

Bước 3: Tiếp theo chúng ta sẽ thêm các dạng dữ liệu vào các ô bằng phương thức addCell. Để viết dữ liệu vào các ô, chúng ta sẽ có 3 dạng chính: Chuỗi, Số và Công thức lần lượt được tạo bằng Label, Number, Formula. Ví dụ:

sheet.addCell(new Label(0, 0, "Add a String to cell")); sheet.addCell(new Number(0, 1, 100)); sheet.addCell(new Formula(0, 3, "IF(A1=1,"one", "two")"));

Bước 4: Sau khi chúng ta đã thực hiện xong bước 3, chúng ta cần thực hiện lệnh write và close để hoàn tất việc ghi dữ liệu

workbook.write(); workbook.close();

Đọc file Excel với Jxl

Bước 1: Tạo Workbook “trỏ” đến file của bạn.

Workbook workbook = Workbook.getWorkbook(new File(fileName));

Bước 2: Lấy Sheet bạn muốn đọc. Bạn có thể lấy theo vị trí sheet hoặc tên Sheet

Sheet sheet = workbook.getSheet(0);

Bước 3: Đọc nội dung từng ô trong bảng tính. Nếu bạn muốn lấy nội dung của một ô nào đó bạn có thể làm như sau: sheet.getCell(col, row).getContents(). Tuy nhiên nếu bạn muốn đọc toàn bộ các ô trong bảng tính hãy lấy hàng và cột cuối cùng chứa dữ liệu bằng sheet.getRows() và sheet.getColumns(), và dùng vòng lặp for để đọc từng ô. Sau khi đọc xong, chúng ta cũng cần close workbook như khi viết dữ liệu

for (int row = 0; row < rows; row++) { for (int col = 0; col < cols; col++) { Cell cell = sheet.getCell(col, row); System.out.print(cell.getContents() + "t"); } System.out.println("n"); } workbook.close();

Mở và ghi thêm dữ liệu vào Excel với Jxl

Để mở và ghi thêm dữ liệu vào file Excel, trước tiên chúng ta cần lấy Workbook từ file Excel cần viết thêm giống như khi chúng ta đọc. Sau đó tạo một WritableWorkbook đến chính workbook vừa lấy và chúng ta sẽ làm việc với WritableWorkbook này bình thường.

Workbook workbook = Workbook.getWorkbook(new File(fileName)); WritableWorkbook writeWorkbook = Workbook.createWorkbook(new File(fileName), workbook);

Demo code

package vietSource.net.IOFile; import java.io.File; import java.io.IOException; import java.util.Scanner; import jxl.Cell; import jxl.Sheet; import jxl.Workbook; import jxl.read.biff.BiffException; import jxl.write.Formula; import jxl.write.Label; import jxl.write.WritableSheet; import jxl.write.WritableWorkbook; import jxl.write.WriteException; import jxl.write.biff.RowsExceededException; /** */ public class ReadWriteExcel { private final String fileName = "/home/nguyenvanquan7826/Desktop/nguyenvanquan7826.xls"; private Object[][] data = { { "STT", "Họ và tên", "Điểm", "Xếp loại" }, { "1", "Nguyễn Văn Quân", "9.0", "" }, { "2", "Phạm Thị Hà", "8.0", "" }, { "3", "Nguyễn Bá Cường", "8.5", "" }, { "4", "Vũ Công Tịnh", "9.0", "" }, { "5", "Phạm Trọng Khang", "8", "" }, { "6", "Mai Văn Tài", "8", "" } }; private void writeFileExcel() { WritableWorkbook workbook; try { workbook = Workbook.createWorkbook(new File(fileName)); WritableSheet sheet1 = workbook.createSheet("KTPM K10B", 0); sheet1.addCell(new Label(0, 0, "DANH SÁCH SINH VIÊN TIÊU BIỂU")); int rowBegin = 2; int colBegin = 0; for (int row = rowBegin, i = 0; row < data.length + rowBegin; row++, i++) { for (int col = colBegin, j = 0; col < data[0].length + colBegin; col++, j++) { Object obj = data[i][j]; sheet1.addCell(new Label(col, row, (String) data[i][j])); } } workbook.write(); workbook.close(); } catch (IOException e) { System.out.println("Error create file " + e.toString()); } catch (RowsExceededException e) { System.out.println("Error write file " + e.toString()); } catch (WriteException e) { System.out.println("Error write file " + e.toString()); } System.out.println("create and write success"); } private void readFileExcel() { Workbook workbook; try { workbook = Workbook.getWorkbook(new File(fileName)); Sheet sheet = workbook.getSheet(0); int rows = sheet.getRows(); int cols = sheet.getColumns(); System.out.println("Data in file:"); for (int row = 0; row < rows; row++) { for (int col = 0; col < cols; col++) { Cell cell = sheet.getCell(col, row); System.out.print(cell.getContents() + " "); } System.out.println(" "); } workbook.close(); } catch (BiffException e) { System.out.println("File not found " + e.toString()); } catch (IOException e) { System.out.println("File not found " + e.toString()); } } private void openAndWriteFileExcel() { Workbook workbook; WritableWorkbook writeWorkbook; try { workbook = Workbook.getWorkbook(new File(fileName)); writeWorkbook = Workbook.createWorkbook(new File(fileName), workbook); WritableSheet sheet1 = writeWorkbook.getSheet(0); int col = 3; int rowBegin = 3; for (int row = rowBegin; row < data.length + rowBegin - 1; row++) { Formula f = new Formula(col, row, "IF(C" + (row + 1) sheet1.addCell(f); } writeWorkbook.write(); writeWorkbook.close(); } catch (IOException e) { System.out.println("File not found " + e.toString()); } catch (RowsExceededException e) { System.out.println("File not found " + e.toString()); } catch (WriteException e) { System.out.println("File not found " + e.toString()); } catch (BiffException e) { System.out.println("File not found " + e.toString()); } System.out.println("open and write success"); } private void showMenu() { System.out.println(); System.out.println("Select an integer for process:"); System.out.println("1 - Create new file and wrire data"); System.out.println("2 - Read file exits"); System.out.println("3 - Open and write to file exits"); } public static void main(String[] args) { ReadWriteExcel rwExcel = new ReadWriteExcel(); while (true) { rwExcel.showMenu(); Scanner scan = new Scanner(System.in); int select = Integer.parseInt(scan.nextLine()); switch (select) { case 1: rwExcel.writeFileExcel(); break; case 2: rwExcel.readFileExcel(); break; case 3: rwExcel.openAndWriteFileExcel(); break; default: scan.close(); break; } } } }

Bạn đang đọc nội dung bài viết Đọc Ghi Excel File Sử Dụng Apache Poi trên website Beiqthatgioi.com. Hy vọng một phần nào đó những thông tin mà chúng tôi đã cung cấp là rất hữu ích với bạn. Nếu nội dung bài viết hay, ý nghĩa bạn hãy chia sẻ với bạn bè của mình và luôn theo dõi, ủng hộ chúng tôi để cập nhật những thông tin mới nhất. Chúc bạn một ngày tốt lành!