Top 3 # Xem Nhiều Nhất Xuất File Word Trong Java Mới Nhất 3/2023 # Top Like | Beiqthatgioi.com

Đọ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 Và Ghi File Trong Java (Bài 5)

Đọc và ghi file trong java là các hoạt động nhập/xuất dữ liệu (nhập dữ liệu từ bàn phím, đọc dữ liệu từ file, ghi dữ liệu lên màn hình, ghi ra file, ghi ra đĩa, ghi ra máy in…) đều được gọi là luồng (stream).

Đọc và ghi file trong java – Các loại luồng dữ liệu

Bước 1: Tạo đối tượng luồng và liên kết với nguồn dữ liệu.

Bước 2: Thao tác dữ liệu (đọc hoặc ghi hoặc cả hai).

Bước 3: Đóng luồng.

Xử lý nhập xuất dữ liệu sử dụng luồng byte

Sử dụng luồng byte trong các trường hợp như nhập xuất kiểu dữ liệu nguyên thủy (như kiểu int, float, double, boolean), nhập xuất kiểu dữ liệu kiểu đối tượng (object)

Đọc và ghi dữ liệu nhị phân (binary data)

package file_handling; import java.io.DataOutputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; /** * * @author chúng tôi */ public class DataOutputExample { public static void main(String[] args) { try {

Ví dụ 2: Đọc dữ liệu chứa trong tập tin d:/mydata.bin với DataInputStream

package file_handling; import java.io.DataInputStream; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; /** * * @author chúng tôi */ public class DataInputExample { public static void main(String[] args) { try {

Ví dụ 3: Đọc và ghi dữ liệu kiểu object

Tạo lớp Stock và lớp này phải cài đặt giao diện Serializable

package file; import java.io.Serializable; /** * * @author chúng tôi */ public class Stock implements Serializable{ private int id; private String desc; private double price; private int quantity; public Stock(int id, String desc, double price, int quantity) { chúng tôi = id; chúng tôi = desc; this.price = price; this.quantity = quantity; } @Override public String toString() { return id + "-" + desc + "-" + price + "-" + quantity; } }

Tạo lớp ObjectOutputExample dùng để ghi dữ liệu kiểu object

package file; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; /** * * @author chúng tôi */ public class ObjectOutputExample { public static void main(String[] args) { try {

Tạo lớp ObjectInputExample dùng để đọc dữ liệu kiểu object

package file; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.ObjectInputStream; /** * * @author chúng tôi */ public class ObjectInputExample { public static void main(String[] args) { try {

Xử lý nhập xuất dữ liệu bằng luồng character

Luồng byte rất mạnh mẽ và linh hoạt. Tuy nhiên nếu bạn muốn lưu trữ file chứa văn bản Unicode thì luồng character là lựa chọn tốt nhất vì ưu điểm của luồng character là nó thao tác trực tiếp trên ký tự Unicode.

Tất cả các luồng character đều được kế thừa từ 2 lớp Reader và Writer

Ví dụ 1: Ghi dữ liệu với FileWriter

package file_handling; import java.io.File; import java.io.FileWriter; import java.io.IOException; /** * * @author chúng tôi */ public class FileWriterExample { public static void main(String[] args) { try {

Ví dụ 2: Đọc dữ liệu với FileReader

package file_handling; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; /** * * @author chúng tôi */ public class FileReaderExample { public static void main(String[] args) { try {

Đọc và ghi file trong java – Thực hành

Tạo package tên file và thực hiện các yêu cầu bên dưới

Bài thực hành số 1: Tạo lớp NhanVien có các thuộc tính mã nhân viên, họ tên, tuổi và lương.

Viết setter, getter, constructor và toString.

Viết phương thức cho phép nhập thông tin cho 3 nhân viên từ bàn phím. Sử dụng FileWriter để ghi thông tin vào nhanvien.txt.

Viết phương thức để đọc nội dung file chúng tôi và in những gì đọc được từ file ra màn hình.

Bài thực hành số 2: Tạo lớp mới và thực hiện các xử lý sau

Viết phương thức tạo mảng 3 nhân viên, nhập thông tin cho các nhân viên, sử dụng ObjectOutputStream để ghi mảng đối tượng nhân viên vào file nhanvien.bin

Viết phương thức để đọc file chúng tôi và in mảng nhân viên ra màn hình.

Tạo File Pdf Trong Java, Sử Dụng Flying Saucer Và Thymeleaf

Chắc hẳn các bạn đã quá quen thuộc với các file định dạng PDF. Nào là CV, các văn bản đặc tả spec, các công văn, báo cáo, các vé điện tử .v.v.v Điều đó đặt ra yêu cầu các ứng dụng web phải có khả năng xuất file PDF với format nào đó phù hợp với từng yêu cầu của hệ thống chức năng. Bài viết hôm nay của mình sẽ hướng dẫn các bạn dùng Java để thực hiện điều đó!

Trong bài này, các bạn sẽ thấy, quá trình xuất file PDF của mình gồm 2 bước chính như sau

Sử Thymeleaf để đưa dữ liệu vào mẫu và từ đó nhận được document dạng XHTML với các data đã được bind. Mình ví dụ hình trên, $$name} được gán với giá trị Thomas

Save document XHTML đó dưới dạng PDF sử dụng Flying Saucer.

Lưu ý rằngm 2 bước trên là hoàn toàn đoọc lập. Chúng ta có thể dễ dàng sử dụng các template engine khác (ví dụ như Apache FreeMarker) hay thậm chí là HTML thuần. Tuy nhiên, bài viết này sử dụng Thymeleaf là bởi vì Thymeleaf là 1 template engine rất phổ biến được biệt là khi làm việc với Spring

Để bắt đầu, chúng ta cần 3 dependencies

compile group: 'org.thymeleaf', name: 'thymeleaf', version: '3.0.6.RELEASE' compile group: 'org.xhtmlrenderer', name: 'flying-saucer-core', version: '9.1.6' compile group: 'org.xhtmlrenderer', name: 'flying-saucer-pdf-itext5', version: '9.1.6'

Đầu tiên, để đơn giản cho các bạn dễ hình dung, mình sẽ sử dụng 1 ví dụ đơn giản trước, Ở đây Thymeleaf Template mình tạo đơn giản như sau

và đển render template này với ThymeLeaf, bạn có thể sử dụng đoạn code sau

Và như thế, bạn đã có 1 chuỗi là chuỗi htlml sau khi bind dữ liệu (name = Thomas).

Việc tiếp theo là sử dụng chuỗi này cho việc chuyển hóa sang PDF thôi.

Chú ý rằng, ví dụ này của mình chỉ là 1 ví dụ vô cùng đơn giản. ThymeLeaf thực tế còn mạnh hơn rất nhiều với việc cung cấp các cấu trúc lệnh for, if và gọi lệnh Java trong template. Bạn có thể tìm được rất nhiều các vi dụ và hướng dẫn trên internet

Chia sẻ tin đăng đến bạn bè

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

Đọc ghi file Excel bằng Java sử dụng 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…

1.1 Xử lý file Excel với Apache POI

Apache POI xử lý các thành phần trong excel theo đúng lập trình hướng đối tượng – mỗi thành phần trong Excel đều được coi như 1 đối tượng.

Các class cơ bản được dùng để đọc ghi file Excel

HSSF: các class có tên bắt đầu là HSSF được dùng để sử lý các file Microsoft Excel 2003 (.xls)

XSSF: các class có tên bắt đầu là XSSF được dùng để sử lý các file Microsoft Excel 2007 trở về sau (.xlsx)

XSSFWorkbook và HSSFWorkbook là các class xử lý với Excel Workbook

HSSFSheet và XSSFSheet là các class xử lý với Excel Worksheet

Row: định nghĩa một dòng trong excel

Cell: định nghĩa một ô trong excel

Ở đây mình sử dụng maven để lấy thư viện của Apache POI.

Cho các file Microsoft Excel 2003

Cho các file Microsoft Excel 2007 trở về sau

3.1 Ghi file Excel

Tạo 1 Worksheet có name là “Customer_Info”

dòng đầu tiên hiển thị “List Of Customer”

Các dòng tiếp theo hiển thị các thông tin của customer (id, name, email), mỗi thông tin ở 1 column.

package stackjava.com.apachepoiexcel.demo; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.ArrayList; import java.util.List; 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; public class WriteFileExcel { public static void main(String[] args) { System.out.println("Create file excel"); XSSFWorkbook workbook = new XSSFWorkbook(); XSSFSheet sheet = workbook.createSheet("Customer_Info"); int rowNum = 0; Row firstRow = sheet.createRow(rowNum++); Cell firstCell = firstRow.createCell(0); firstCell.setCellValue("List of Customer"); listOfCustomer.add(new Customer(1, "Sylvester Stallone", "abc@gmail.com")); listOfCustomer.add(new Customer(2, "Tom Cruise", "xyz@yahoo.com")); listOfCustomer.add(new Customer(3, "Vin Diesel", "abc@hotmail.com")); for (Customer customer : listOfCustomer) { Row row = sheet.createRow(rowNum++); Cell cell1 = row.createCell(0); cell1.setCellValue(customer.getId()); Cell cell2 = row.createCell(1); cell2.setCellValue(customer.getName()); Cell cell3 = row.createCell(2); cell3.setCellValue(customer.getEmail()); } try { FileOutputStream outputStream = new FileOutputStream("Demo-ApachePOI-Excel.xlsx"); workbook.write(outputStream); workbook.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } System.out.println("Done"); } } package stackjava.com.apachepoiexcel.demo; public class Customer { private int id; private String name; private String email; }

Kết quả:

Bây giờ mình sẽ thực hiện đọc lại file Excel vừa tạo ở trên:

package stackjava.com.apachepoiexcel.demo; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.DataFormatter; 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 ReadFileExcel { public static void main(String[] args) { try { FileInputStream excelFile = new FileInputStream(new File("Demo-ApachePOI-Excel.xlsx")); Workbook workbook = new XSSFWorkbook(excelFile); Sheet datatypeSheet = workbook.getSheetAt(0); DataFormatter fmt = new DataFormatter(); Row firstRow = iterator.next(); Cell firstCell = firstRow.getCell(0); System.out.println(firstCell.getStringCellValue()); while (iterator.hasNext()) { Row currentRow = iterator.next(); Customer customer = new Customer(); customer.setId(Integer.parseInt(fmt.formatCellValue(currentRow.getCell(0)))); customer.setName(currentRow.getCell(1).getStringCellValue()); customer.setEmail(currentRow.getCell(2).getStringCellValue()); listOfCustomer.add(customer); } for (Customer customer : listOfCustomer) { System.out.println(customer); } workbook.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } }

*Lưu ý: id của customer là integer nên khi ghi vào file excel nó sẽ là kiểu numeric, do đó khi đọc ra thì nó sẽ đọc là numeric và chuyển thành double, ví dụ 1 sẽ là 1.0. Do đó ta dùng DataFormatter để định dạng nó về kiểu string và parse lại thành integer.

Kết quả:

List of Customer Customer [id=1, name=Sylvester Stallone, email=abc@gmail.com] Customer [id=2, name=Tom Cruise, email=xyz@yahoo.com] Customer [id=3, name=Vin Diesel, email=abc@hotmail.com]

Okay, Done!

Đọc ghi file Excel bằng Java sử dụng Apache POI

Reference: