Java導入數據到Excel表格(poi方式)

例子:
下載poi jar包的地址:http://download.csdn.net/download/pumpkin09/7077011

package test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

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.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Font;
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.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFCellStyle;

public class ExcelTest {

    public static void main(String[] args) {
        //導入數據到excel表格

        List<Student> studentList = new ArrayList<Student>();

        Student student1 = new Student("小璐", "女", "20", "大學", "湖南工學院", "李四",
                "廣東", "深圳", "白石洲", "123456");
        Student student2 = new Student("小花", "女", "22", "aaa", "湖南工學院", "張三",
                "湖南", "婁底", "新化", "453456");
        Student student3 = new Student("小胡", "女", "23", "大學", "湖南工學院", "王五",
                "廣東", "深圳", "桃園", "138456");
        studentList.add(student1);
        studentList.add(student2);
        studentList.add(student3);

        //首次  會創建表格
/*      HSSFWorkbook wb=exportExcelForStudent(studentList);
        try {
            File f=new File("d:\\text3.xls");
            if(!f.exists()){
                f.createNewFile();
            }
            FileOutputStream fos = new FileOutputStream(f);
            wb.write(fos);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("文件失敗");
        }*/

        //追加  在已有的表格上追加
        POIFSFileSystem ps;
        try {
            FileInputStream fs=new FileInputStream("d:\\text3.xls");  //獲取d://test.xls 
            ps = new POIFSFileSystem(fs);//使用POI提供的方法得到excel的信息  
             HSSFWorkbook wb2=new HSSFWorkbook(ps);    
                HSSFSheet sheet=wb2.getSheetAt(0);  //獲取到工作表,因爲一個excel可能有多個工作表  
                HSSFRow row=sheet.getRow(0);  //獲取第一行(excel中的行默認從0開始,所以這就是爲什麼,一個excel必須有字段列頭),即,字段列頭,便於賦值  
                System.out.println(sheet.getLastRowNum()+" "+row.getLastCellNum());  //分別得到最後一行的行號,和一條記錄的最後一個單元格  
                Font font0 = createFonts(wb2, Font.BOLDWEIGHT_BOLD, "宋體", false,  
                        (short) 200);  
                Font font1 = createFonts(wb2, Font.BOLDWEIGHT_NORMAL, "宋體", false,  
                        (short) 200);  
                FileOutputStream out=new FileOutputStream("d:\\text3.xls");  //向d://test.xls中寫數據  


/*              createCell(wb2, row, 0, "leilei", font1);
                createCell(wb2, row, 1, "女", font1);
                createCell(wb2, row, 2, "25", font1);
                createCell(wb2, row, 3, "研究生", font1);
                createCell(wb2, row, 4, "中南", font1);
                createCell(wb2, row, 5, "張三", font1);
                createCell(wb2, row, 6, "湖南", font1);
                createCell(wb2, row, 7, "123456", font1);*/

                for(int i=0;i<studentList.size();i++){
                    Student stu=studentList.get(i);
                    row=sheet.createRow((short)(sheet.getLastRowNum()+1)); //在現有行號後追加數據  
                    createCell(wb2, row, 0, stu.getName(), font1);
                    createCell(wb2, row, 1, stu.getStudentsex(), font1);
                    createCell(wb2, row, 2, stu.getStudentage(), font1);
                    createCell(wb2, row, 3, stu.getGrade(), font1);
                    createCell(wb2, row, 4, stu.getStudentarea(), font1);
                    createCell(wb2, row, 5, stu.getStudentschool(), font1);
                    createCell(wb2, row, 6, stu.getParents(), font1);
                    createCell(wb2, row, 7, stu.getContact(), font1);
                }

                out.flush();  
                wb2.write(out);    
                out.close();    
                System.out.println(row.getPhysicalNumberOfCells()+" "+row.getLastCellNum());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } 






    }

    public static HSSFWorkbook exportExcelForStudent(List<Student> studentList) {
        // 創建excel文件對象
        HSSFWorkbook wb = new HSSFWorkbook();

        // 創建一個張表
        Sheet sheet = wb.createSheet();
        // 創建第一行
        Row row = sheet.createRow(0);
        // 創建第二行
        //Row row1 = sheet.createRow(1);
        // 文件頭字體
        Font font0 = createFonts(wb, Font.BOLDWEIGHT_BOLD, "宋體", false,
                (short) 200);
        Font font1 = createFonts(wb, Font.BOLDWEIGHT_NORMAL, "宋體", false,
                (short) 200);
        /*// 合併第一行的單元格
        sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 1));
        // 設置第一列的文字
        createCell(wb, row, 0, "總數", font0);
        // 合併第一行的2列以後到8列(不包含第二列)
        sheet.addMergedRegion(new CellRangeAddress(0, 0, 2, 8));
        // 設置第二列的文字
        createCell(wb, row, 2, "基本信息", font0);*/
        // 給第二行添加文本
    /*  createCell(wb, row, 0, "序號", font1);
        createCell(wb, row, 1, "版本", font1);*/
        createCell(wb, row, 0, "姓名", font1);
        createCell(wb, row, 1, "性別", font1);
        createCell(wb, row, 2, "年齡", font1);
        createCell(wb, row, 3, "年級", font1);
        createCell(wb, row, 4, "學校", font1);
        createCell(wb, row, 5, "父母名稱", font1);
        createCell(wb, row, 6, "籍貫", font1);
        createCell(wb, row, 7, "聯繫方式", font1);
        // 第三行表示
        int l = 2;

        // 這裏將學員的信息存入到表格中
        for (int i = 0; i < studentList.size(); i++) {
            // 創建一行
            Row rowData = sheet.createRow(l++);
            Student stu = studentList.get(i);
    /*      createCell(wb, rowData, 0, String.valueOf(i + 1), font1);
            createCell(wb, rowData, 1, "3.0", font1);*/
            createCell(wb, rowData, 0, stu.getName(), font1);
            createCell(wb, rowData, 1, stu.getStudentsex(), font1);
            createCell(wb, rowData, 2, stu.getStudentage(), font1);
            createCell(wb, rowData, 3, stu.getGrade(), font1);
            createCell(wb, rowData, 4, stu.getStudentschool(), font1);
            createCell(wb, rowData, 5, stu.getParents(), font1);
            createCell(wb,rowData,6,stu.getStudentprovince() + stu.getStudentcity()+ stu.getStudentarea(), font1);
            createCell(wb, rowData, 7, stu.getContact(), font1);

        }
        return wb;
    }

    /**
     * 創建單元格並設置樣式,值
     * 
     * @param wb
     * @param row
     * @param column
     * @param
     * @param
     * @param value
     */
    public static void createCell(Workbook wb, Row row, int column,
            String value, Font font) {
        Cell cell = row.createCell(column);
        cell.setCellValue(value);
        CellStyle cellStyle = wb.createCellStyle();
        cellStyle.setAlignment(XSSFCellStyle.ALIGN_CENTER);
        cellStyle.setVerticalAlignment(XSSFCellStyle.VERTICAL_BOTTOM);
        cellStyle.setFont(font);
        cell.setCellStyle(cellStyle);
    }

    /**
     * 設置字體
     * 
     * @param wb
     * @return
     */
    public static Font createFonts(Workbook wb, short bold, String fontName,
            boolean isItalic, short hight) {
        Font font = wb.createFont();
        font.setFontName(fontName);
        font.setBoldweight(bold);
        font.setItalic(isItalic);
        font.setFontHeight(hight);
        return font;
    }

    /**
     * 判斷是否爲數字
     * 
     * @param str
     * @return
     */
    public static boolean isNumeric(String str) {
        if (str == null || "".equals(str.trim()) || str.length() > 10)
            return false;
        Pattern pattern = Pattern.compile("^0|[1-9]\\d*(\\.\\d+)?$");
        return pattern.matcher(str).matches();
    }



    /**
     * 刪除指定行
     * @throws Exception 
     */
    public void delRow() throws Exception{

        FileInputStream is = new FileInputStream("d://test.xls");  

        HSSFWorkbook workbook = new HSSFWorkbook(is);  

        HSSFSheet sheet = workbook.getSheetAt(0);  

        sheet.shiftRows(1, 1, 1); //刪除第4行  

        FileOutputStream os = new FileOutputStream("d://test.xls");  

        workbook.write(os);  

        is.close();  

        os.close();  
    }    
}
package test;

public class Student {
    private String name;
    private String studentsex;
    private String grade;
    private String studentschool;
    private String parents;
    private String studentprovince;
    private String studentcity;
    private String studentarea;
    private String contact;
    private String studentage;

    public Student(String name, String studentsex,String studentage, String grade,
            String studentschool, String parents, String studentprovince,
            String studentcity, String studentarea, String contact) {
        super();
        this.name = name;
        this.studentsex = studentsex;
        this.studentage=studentage;
        this.grade = grade;
        this.studentschool = studentschool;
        this.parents = parents;
        this.studentprovince = studentprovince;
        this.studentcity = studentcity;
        this.studentarea = studentarea;
        this.contact = contact;
    }

    public String getName() {
        return name;
    }

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

    public String getStudentsex() {
        return studentsex;
    }

    public void setStudentsex(String studentsex) {
        this.studentsex = studentsex;
    }

    public String getGrade() {
        return grade;
    }

    public void setGrade(String grade) {
        this.grade = grade;
    }

    public String getStudentschool() {
        return studentschool;
    }

    public void setStudentschool(String studentschool) {
        this.studentschool = studentschool;
    }

    public String getParents() {
        return parents;
    }

    public void setParents(String parents) {
        this.parents = parents;
    }

    public String getStudentprovince() {
        return studentprovince;
    }

    public void setStudentprovince(String studentprovince) {
        this.studentprovince = studentprovince;
    }

    public String getStudentcity() {
        return studentcity;
    }

    public void setStudentcity(String studentcity) {
        this.studentcity = studentcity;
    }

    public String getStudentarea() {
        return studentarea;
    }

    public void setStudentarea(String studentarea) {
        this.studentarea = studentarea;
    }

    public String getContact() {
        return contact;
    }

    public void setContact(String contact) {
        this.contact = contact;
    }

    public String getStudentage() {
        return studentage;
    }

    public void setStudentage(String studentage) {
        this.studentage = studentage;
    }

    @Override
    public String toString() {
        return "Student [name=" + name + ", studentsex=" + studentsex
                + ", grade=" + grade + ", studentschool=" + studentschool
                + ", parents=" + parents + ", studentprovince="
                + studentprovince + ", studentcity=" + studentcity
                + ", studentarea=" + studentarea + ", contact=" + contact
                + ", studentage=" + studentage + "]";
    }





}
發佈了24 篇原創文章 · 獲贊 21 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章