Top 10 # Xem Nhiều Nhất Xử Lý File Excel Trong Java Mới Nhất 6/2023 # Top Like | Beiqthatgioi.com

Cách Xử Lý Lỗi File Excel Không Mở Được

Chắc chắn có nhiều trường hợp bạn tải file excel về máy tính hoặc copy file excel ở đâu đó về nhưng không mở được trên máy tính. Vậy nguyên nhân do đâu? Hướng dẫn xử lý lỗi file Excel không mở được, chắc chắn rất cần thiết trong trường hợp bạn đang gặp phải.

Xử lý lỗi file Excel không mở được

Đây là tính năng giúp sửa lỗi trên file Excel.

Bước 2: Tìm kiếm file, lúc này bạn tìm đến file Excel muốn khôi phục. Chú ý vào biểu tượng tam giác cạnh Open, xổ xuống sẽ thấy tính năng Open and Repair.

Bước 3: Thông báo của Microsoft Excel lúc này bạn bấm vào Repair tiến hành sửa chữa file excel.

Hoặc chọn Extract Data mục đích trích lấy dữ liệu bên trong file excel.

2. Chọn tính toán file Excel chuyển sang thủ công

Bước 2: Khi bạn đang trong giao diện Excel Options, chọn Formulas, Workbook Calculation chuyển sang Manual, nhớ bấm ok để lưu lại.

3. Dùng Easy Office Recovery

Để thực hiện năng phục hồi file bạn cần truy cập vào: https://www.munsoft.com/EasyOfficeRecovery/

Trong cửa sổ xuất hiện chọn vào Open File và tìm đến file Excel bị lỗi.

Bước 3: Bấm chọn Browse để chọn vị trí lưu file mới sau. Bấm vào Next.

Khi nào xuất hiện thông báo: Files were successfully recovered có nghĩa là bạn đã khôi phục file thành công rồi đó.

4. Thay đổi thiết lập Protect View

Tính năng này của Excel giúp bảo vệ tự động trước file excel lạ và không rõ nguồn gốc. Đôi khi tính năng này khiến file đó không mở hoặc xung đột khiến file không mở được trên máy tính.

Tính năng Protect View bảo vệ những gì? Các lệnh macro tự động, virus đính kèm theo file, các phép tính toán phức tạp…đều bị tính năng này chặn.

Cách tắt protect view

Mở Excel 2010, tốt nhất hãy tạo workbook mới.

Vào thẻ File chọn Options

Trong Excel Options, chọn Trust center Settings

Trong phần Trust center, tìm tới Protect view. Hãy bỏ đánh dấu hết 3 mục như hình ảnh bên dưới nhé:

Lưu ý: Sau khi tắt tính năng Protect view, mở file Excel thành công, chúng ta nên thiết lập lại cơ chế bảo vệ tự động nhằm bảo vệ Excel trước các file lạ hoặc virus.

5. Sửa lại chương trình

Đôi khi có vài trường hợp Office bị lỗi và chúng ta phải thử bằng cách sửa lại chương trình. Các bạn thực hiện như sau:

1. Bấm vào nút Start trên máy tính, chọn vào Control Pannel

3. Chọn Microsoft Office (phiên bản 2010)

5. Chạy xong quá trình sửa lỗi chúng ta nên khởi động lại máy tính và thử mở lại file excel.

Đọ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; } } } }

Đọ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 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: