Java는 Excel 테이블을 생성하고 데이터를 가져오며 Excel 템플릿에 따라 데이터를 가져옵니다.

50723 단어 기능 코드
배경: 프로젝트에서 메일 발송 기능을 사용하려면 데이터를 excel 표에 가져와 공급업체에 보내야 한다. 처음에 excel을 직접 만들었을 때 리더가 못생겼다고 해서 갑에게 템플릿을 달라고 했다. 그래서 본 글은 excel을 직접 생성하여 데이터를 가져오는 기능을 소개하는 것 외에 고정된 템플릿에 따라 데이터를 가져오는 기능도 소개한다.

1. Excel을 새로 생성하고 데이터를 가져옵니다.

package com.tdhc.common.util;

import com.tdhc.common.model.PuEnquiry;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.ByteArrayOutputStream;
import java.util.List;

/**
 *  excel , 
 */
public class CreateExcel {
    public static ByteArrayOutputStream CreateExccel(List<PuEnquiry> list){
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        // 
        Workbook workbook = new XSSFWorkbook();
        //  
        XSSFSheet sheet = (XSSFSheet) workbook.createSheet("sheet1");
        // 
        Row row = sheet.createRow(0);

        row.createCell(0).setCellValue(" ");
        row.createCell(1).setCellValue(" ");
        row.createCell(2).setCellValue(" ");
        row.createCell(3).setCellValue(" ");
        row.createCell(4).setCellValue(" ");
        row.createCell(5).setCellValue(" ");
        row.createCell(6).setCellValue(" ");
        row.createCell(7).setCellValue(" ");
        row.createCell(8).setCellValue(" / ");
        row.createCell(9).setCellValue(" ");
        row.createCell(10).setCellValue(" ");
        row.createCell(11).setCellValue(" ");
        row.createCell(12).setCellValue(" ");
        row.createCell(13).setCellValue(" ");
        row.createCell(14).setCellValue(" ");
        for(int i=1;i<list.size();i++) {
            XSSFRow row1 = sheet.createRow(i);
            row1.createCell(0).setCellValue(list.get(i-1).getEnquirynum());
            row1.createCell(1).setCellValue(list.get(i-1).getDocumentcode());
            row1.createCell(2).setCellValue(list.get(i-1).getMatname());
            row1.createCell(3).setCellValue(list.get(i-1).getSpecification());
            row1.createCell(4).setCellValue(list.get(i-1).getUnit());
            row1.createCell(5).setCellValue(list.get(i-1).getDeclarequantity());
            row1.createCell(6).setCellValue(list.get(i-1).getUnitprice());
            row1.createCell(7).setCellValue(list.get(i-1).getReadydate());
            row1.createCell(8).setCellValue(list.get(i-1).getCargoinfo());
            row1.createCell(9).setCellValue(list.get(i-1).getEffectivedate());
            row1.createCell(10).setCellValue(list.get(i-1).getSupname());
            row1.createCell(11).setCellValue(list.get(i-1).getSupshortname());
            row1.createCell(12).setCellValue(list.get(i-1).getSupemail());
            row1.createCell(13).setCellValue(list.get(i-1).getSuplinkman());
            row1.createCell(14).setCellValue(list.get(i-1).getSuplinkmanphone());
        }
        try {
            workbook.write(baos);
            baos.close();
        }catch (Exception e){
            e.printStackTrace();
        }
        return baos;
    }
}

단계: 작업 목록 만들기 – 테이블 만들기 – 줄 만들기 – 셀 만들기 – 작업 셀 비고: 방법의 반환값과 작업 흐름을 상관하지 않습니다. 왜냐하면 저는 메일에 맞추어 excel 첨부 파일을 보내기 위해 그렇게 했습니다. 워크북을 setCellValue로 만드는 것만 주목하면 됩니다.

2. 고정된 excel 템플릿에 따라 데이터 가져오기

package com.tdhc.common.util;

import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.xssf.usermodel.examples.CreateCell;

import java.io.*;
import java.util.List;

public class CreateExcelAsTemp {
    public static ByteArrayOutputStream CreateExcel(List<Person> list) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        //  
        FileInputStream fis = new FileInputStream("F:/test.xlsx");
        XSSFWorkbook workBook = new XSSFWorkbook(fis);

        //  ( sheet)
        XSSFSheet sheet = workBook.cloneSheet(0);
        workBook.setSheetName(1, " "); //  sheet 
        workBook.removeSheetAt(0);
        XSSFCellStyle cellStyle = workBook.createCellStyle();
        cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN); // 
        cellStyle.setBottomBorderColor(IndexedColors.BLACK.getIndex());// 
        cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN);// 
        cellStyle.setLeftBorderColor(IndexedColors.BLACK.getIndex()); //  
        cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN);// 
        cellStyle.setTopBorderColor(IndexedColors.BLACK.getIndex());  //  
        cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN);// 
        cellStyle.setRightBorderColor(IndexedColors.BLACK.getIndex());  //  
        cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); //  

        for (int i=10;i<list.size()+10;i++){
            Row row = sheet.createRow(i);

            Cell cell = row.createCell(0);
            cell.setCellStyle(cellStyle);
            cell.setCellValue(i-9);

            Cell cell1 = row.createCell(1);
            cell1.setCellStyle(cellStyle);
            cell1.setCellValue((list.get(i-10).getName()));

            Cell cell2 = row.createCell(2);
            cell2.setCellStyle(cellStyle);
            cell2.setCellValue(list.get(i-10).getAge());

            Cell cell3 = row.createCell(3);
            cell3.setCellStyle(cellStyle);
            cell3.setCellValue(list.get(i-10).getAddress());

            Cell cell4 = row.createCell(4);
            cell4.setCellStyle(cellStyle);
            cell4.setCellValue(list.get(i-10).getBirthday());

            Cell cell5 = row.createCell(5);
            cell5.setCellStyle(cellStyle);
            cell5.setCellValue(list.get(i-10).getBirthday());

            Cell cell6 = row.createCell(6);
            cell6.setCellStyle(cellStyle);
            cell6.setCellValue(list.get(i-10).getAaa());

            Cell cell7 = row.createCell(7);
            cell7.setCellStyle(cellStyle);
            cell7.setCellValue(list.get(i-10).getBbb());

            Cell cell8 = row.createCell(8);
            cell8.setCellStyle(cellStyle);
            cell8.setCellValue(list.get(i-10).getCcc());

            Cell cell9 = row.createCell(9);
            cell9.setCellStyle(cellStyle);
            cell9.setCellValue(list.get(i-10).getDdd());
        }

        try {
            workBook.write(baos);
            baos.close();
            /*FileOutputStream fileOutputStream = new FileOutputStream("F:/aaa.xlsx");
            workBook.write(fileOutputStream);
            fileOutputStream.close();*/
        }catch (Exception e){
            e.printStackTrace();
        }
        return baos;
    }
}

단계: 디스크에서 원본 파일 읽기 – 원본 파일 복제 sheet – 작업 (이후 첫 번째 작업과 유사하게 스타일 설정 코드가 많아진 것은 템플릿에 대응해야 하기 때문이다. 그리고 setCellValue와 SetCellStyle은 한 줄에 동시에 쓸 수 없기 때문에 뒤에 코드가 많아 보인다) 비고: 복제가 끝난 후의 작업은 첫 번째 작업과 유사하다. 여기에는 복제 방식이 사용된다.물론 POI 읽기와 같은 방식으로 효과를 달성하면 된다.
참조된 작업 셀에 대한 기술 블로그:https://www.cnblogs.com/jym-sunshine/p/4917476.html https://www.cnblogs.com/yanjie-java/p/8329276.html이 두 개는 나에게 비교적 유용한 것이다. 물론 다른 사나이의 블로그도 마찬가지로 우수하다. 예가 매우 많기 때문에 관련 기능은 검색하여 참고할 수 있다

좋은 웹페이지 즐겨찾기