《I/O 흐름》poi 조작 엑셀

8218 단어 I/O
가방
다운로드 주소http://central.maven.org/maven2/org/apache/poi/poi/3.15/poi-3.15.jar
Data.java
package com.usc.hjp;

public class Data {
    private String name;
    private String number;

    public Data() {

    }

    public Data(String name, String number) {
        super();
        this.name = name;
        this.number = number;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getNumber() {
        return number;
    }

    public void setNumber(String number) {
        this.number = number;
    }

}

MakeExcelTest .java
package com.usc.hjp;

import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.junit.Test;

/**
 * java to excel   appache poi 3.15 jar  
 */
public class MakeExcelTest {
    protected static List datas = new ArrayList<>();

    public static void saveToExcel(List datas, String filePath) {
        //    ,    workbook    excel  
        HSSFWorkbook workbook = new HSSFWorkbook();
        //    , workbook     sheet  excel  sheet
        HSSFSheet sheet = workbook.createSheet("    ");
        //         
        sheet.setColumnWidth(0, 20 * 256);
        sheet.setColumnWidth(1, 80 * 256);
        //    , sheet       0 ,    poi sheet      
        HSSFRow row = sheet.createRow(0);
        //    ,     ,    
        HSSFCell cell = row.createCell(0);
        cell.setCellValue("   ");
        cell = row.createCell(1);
        cell.setCellValue("  ");
        //    ,      ,               ,      ,     。              
        for (int i = 0; i < datas.size(); i++) {
            HSSFRow row1 = sheet.createRow(i + 1);
            Data data = datas.get(i);
            //        
            row1.createCell(0).setCellValue(data.getName());
            row1.createCell(1).setCellValue(data.getNumber());
        }
        //            
        try {
            FileOutputStream fos = new FileOutputStream(filePath);
            workbook.write(fos);
            System.out.println("    ");
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void Test() {
        //     
        String filePath = "E:\\datas.xls";
        //               
        Data data = new Data();
        data.setName("xx");
        data.setNumber("xx");
        MakeExcelTest.datas.add(data);
        //      data  
        List datas = MakeExcelTest.datas;
        //                
        MakeExcelTest.saveToExcel(datas, filePath);
    }
}

좋은 웹페이지 즐겨찾기