Java是一種通用編程語言,在工作和生活中有著廣泛的應用。在處理數據方面,Java可以實現讀取和下載Excel文檔。下面我們來具體了解一下Java讀取Excel和下載的操作。
1. Java讀取Excel文件
// 導入依賴import org.apache.poi.ss.usermodel.*;
// 讀取Excel
Workbook workbook = WorkbookFactory.create(new FileInputStream("test.xlsx"));
Sheet sheet = workbook.getSheetAt(0);
for (Row row : sheet) {
for (Cell cell : row) {
System.out.print(cell.getStringCellValue() + " ");
}
System.out.println();
}
// 關閉文檔
workbook.close();
2. Java下載Excel文件
// 導入依賴import javax.servlet.ServletOutputStream;
// 下載Excel
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
response.setContentType("application/vnd.ms-excel;charset=UTF-8");
ServletOutputStream outputStream = response.getOutputStream();
Workbook workbook = WorkbookFactory.create(new FileInputStream("test.xlsx"));
workbook.write(outputStream);
workbook.close();
outputStream.flush();
outputStream.close();
以上就是Java讀取Excel和下載的代碼,希望對大家有所幫助。