Java导入数据到Excel表格(poi方式)

例子:
下载poi jar包的地址:http://download.youkuaiyun.com/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 + "]";
    }





}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值