java poi 匯出excel

來源:互聯網
上載者:User

標籤:name   進位   san   put   header   pac   obj   xlsx   pat   

很多時候,一個軟體應用程式需要產生Microsoft Excel檔案格式的報告。有時,一個應用程式甚至希望將Excel檔案作為輸入資料。例如,一個公司開發的應用程式將財務部門需要所有輸出產生自己的Excel。

任何Java程式員願意將MS Office檔案的輸出,可以使用預定義和唯讀API來做到。

 

什麼是Apache POI?

Apache POI是一種流行的API,它允許程式員使用Java程式建立,修改和顯示MS Office檔案。這由Apache軟體基金會開發使用Java分布式設計或修改Microsoft Office檔案的開源庫。它包含類和方法對使用者輸入資料或檔案到MS Office文檔進行解碼。

Apache POI組件

Apache POI包含類和方法,來將MS Office所有OLE 2文檔複合。此API組件的列表如下。

  • POIFS (較差混淆技術實現檔案系統) : 此組件是所有其他POI元件的基本因素。它被用來明確地讀取不同的檔案。

  • HSSF (可怕的試算表格式) : 它被用來讀取和寫入MS-Excel檔案的xls格式。

  • XSSF (XML格式) : 它是用於MS-Excel中XLSX檔案格式。

  • HPSF (可怕的屬性設定格式) : 它用來提取MS-Office檔案屬性設定。

  • HWPF (可怕的文書處理器格式) : 它是用來讀取和寫入MS-Word的文檔副檔名的檔案。

  • XWPF (XML文書處理器格式) : 它是用來讀取和寫入MS-Word的docx副檔名的檔案。

  • HSLF (可怕的投影片版式格式) : 它是用於讀取,建立和編輯PowerPoint簡報。

  • HDGF (可怕的圖表格式) : 它包含類和方法為MS-Visio的二進位檔案。

  • HPBF (可怕的出版商格式) : 它被用來讀取和寫入MS-Publisher檔案。

本人做的事使用java poi匯出excel檔案。因此,僅限於HSSF組件。

ExportUtil工具類:

package net.dagongsoft.framework.util.poi;import java.text.SimpleDateFormat;import java.util.Date;import org.apache.commons.lang.StringUtils;import org.apache.poi.hssf.usermodel.HSSFCell;import org.apache.poi.hssf.usermodel.HSSFCellStyle;import org.apache.poi.hssf.usermodel.HSSFRow;import org.apache.poi.hssf.usermodel.HSSFSheet;import org.apache.poi.hssf.usermodel.HSSFWorkbook;import com.alibaba.fastjson.JSONArray;import com.alibaba.fastjson.JSONObject;/** * @description 利用Java poi匯出excel公用類 * @author ldp * @time 2017年6月8日 下午2:17:08 * */public class ExportUtil {/** * 匯出Excel 97(.xls)格式 ,少量資料 *  * @param title *            sheet名 * @param headString *            列名 * @param jsonArray *            資料集 */public static HSSFWorkbook exportExcel(String title, String headString, JSONArray jsonArray) {// 聲明一個工作薄HSSFWorkbook workbook = new HSSFWorkbook();// 表頭樣式// HSSFCellStyle titleStyle = workbook.createCellStyle();// titleStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);// HSSFFont titleFont = workbook.createFont();// titleFont.setFontHeightInPoints((short) 20);// titleFont.setBoldweight((short) 700);// titleStyle.setFont(titleFont);// 列頭樣式HSSFCellStyle headerStyle = workbook.createCellStyle();// headerStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);// headerStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);// headerStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);// headerStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);// headerStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);// headerStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);// HSSFFont headerFont = workbook.createFont();// headerFont.setFontHeightInPoints((short) 12);// headerFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);// headerStyle.setFont(headerFont);// 儲存格樣式HSSFCellStyle cellStyle = workbook.createCellStyle();// cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);// cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN);// cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);// cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);// cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);// cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);// cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// HSSFFont cellFont = workbook.createFont();// cellFont.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);// cellStyle.setFont(cellFont);// 產生一個表格HSSFSheet sheet = null;if (StringUtils.isNotBlank(title)) {sheet = workbook.createSheet(title);} else {sheet = workbook.createSheet();}String[] headers = headString.split(",");// 遍曆集合資料,產生資料行int rowIndex = 0;int count = 0;if (jsonArray != null) {for (int n = 0; n < jsonArray.size(); n++) {if (rowIndex == 65535 || rowIndex == 0) {if (rowIndex != 0) {count++;// 如果資料超過了,則在第二頁顯示if (StringUtils.isNotBlank(title)) {sheet = workbook.createSheet(title + count);} else {sheet = workbook.createSheet();}}HSSFRow headerRow = sheet.createRow(0); // 列頭 rowIndex =0for (int i = 0; i < headers.length; i++) {headerRow.createCell(i).setCellValue(headers[i]);headerRow.getCell(i).setCellStyle(headerStyle);}rowIndex = 1;// 資料內容從 rowIndex=1開始}JSONObject jo = jsonArray.getJSONObject(n);HSSFRow dataRow = sheet.createRow(rowIndex);for (int i = 0; i < headers.length; i++) {HSSFCell newCell = dataRow.createCell(i);Object o = jo.get(headers[i]);String cellValue = "";if (o == null) {cellValue = "";} else if (o instanceof Date) {cellValue = new SimpleDateFormat("yyyy/MM/dd 00:00:00").format(o);} else {cellValue = o.toString();}newCell.setCellValue(cellValue);newCell.setCellStyle(cellStyle);}rowIndex++;}}// 自動調整寬度for (int i = 0; i < headers.length; i++) {sheet.autoSizeColumn(i);}return workbook;}}

  控制類:

package net.dagongsoft.platform.poi.controller;import java.io.OutputStream;import java.util.ArrayList;import java.util.List;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.poi.hssf.usermodel.HSSFWorkbook;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import com.alibaba.fastjson.JSONArray;import net.dagongsoft.platform.poi.entity.Student;import net.dagongsoft.platform.poi.service.StudentExportService;import net.dagongsoft.platform.poi.util.ExportUtilTest;@Controller@RequestMapping("/studentExportController")public class StudentExportController {@Autowiredprivate StudentExportService studentExportService;@RequestMapping("/export.form")public void exportExcel(HttpServletRequest request, HttpServletResponse response) throws Exception {List<Student> list = new ArrayList<Student>();list.add(new Student(1000, "zhangsan", "20"));list.add(new Student(1001, "lisi", "23"));list.add(new Student(1002, "wangwu", "25"));HSSFWorkbook wb = studentExportService.export(list);response.setContentType("application/vnd.ms-excel");response.setHeader("Content-disposition", "attachment;filename=student.xls");OutputStream ouputStream = response.getOutputStream();wb.write(ouputStream);ouputStream.flush();ouputStream.close();}}

  serivice介面聲明:

package net.dagongsoft.platform.poi.service;import java.util.List;import org.apache.poi.hssf.usermodel.HSSFWorkbook;import net.dagongsoft.platform.poi.entity.Student;public interface StudentExportService {HSSFWorkbook export(List<Student> list);}

  service實作類別:

package net.dagongsoft.platform.poi.service.impl;import java.util.List;import org.apache.poi.hssf.usermodel.HSSFCell;import org.apache.poi.hssf.usermodel.HSSFCellStyle;import org.apache.poi.hssf.usermodel.HSSFRow;import org.apache.poi.hssf.usermodel.HSSFSheet;import org.apache.poi.hssf.usermodel.HSSFWorkbook;import org.springframework.stereotype.Service;import net.dagongsoft.platform.poi.entity.Student;import net.dagongsoft.platform.poi.service.StudentExportService;@Servicepublic class StudentExportServiceImpl implements StudentExportService {String[] excelHeader = { "Id", "Name", "Age" };@Overridepublic HSSFWorkbook export(List<Student> list) {HSSFWorkbook wb = new HSSFWorkbook();HSSFSheet sheet = wb.createSheet("Student");HSSFRow row = sheet.createRow((int) 0);HSSFCellStyle style = wb.createCellStyle();for (int i = 0; i < excelHeader.length; i++) {HSSFCell cell = row.createCell(i);cell.setCellValue(excelHeader[i]);cell.setCellStyle(style);sheet.autoSizeColumn(i);// sheet.SetColumnWidth(i, 100 * 256);}for (int i = 0; i < list.size(); i++) {row = sheet.createRow(i + 1);Student student = list.get(i);row.createCell(0).setCellValue(student.getId());row.createCell(1).setCellValue(student.getName());row.createCell(2).setCellValue(student.getAge());}return wb;}}

  

java poi 匯出excel

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.