Javaによるexcelへのデータの書き込みを簡単に実現

2788 ワード

package com.bdqn.demo.model.entity.User;

public class User {

	private String userName;
	private String password;
	public User(String userName, String password) {
		super();
		this.userName = userName;
		this.password = password;
	}
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	
}

 
import com.bdqn.demo.model.entity.User;
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 java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * java to excel   appache poi 3.15 jar  
 */
public class MakeExcelTest {

    //         
    protected static List getUsers() {
        List users = new ArrayList<>();
        User user1 = new User("admin", "123456");
        User user2 = new User("staff1", "141242");
        User user3 = new User("staff2", "386002");
        users.add(user1);
        users.add(user2);
        users.add(user3);
        return users;
    }


    public static void main(String[] args) {
        //   ,    workbook    excel  
        HSSFWorkbook workbook = new HSSFWorkbook();
        //   , workbook     sheet  excel  sheet
        HSSFSheet sheet = workbook.createSheet("    ");
        //   , sheet       0 ,    poi sheet      
        HSSFRow row = sheet.createRow(0);
        //   ,     ,    
        HSSFCell cell = row.createCell(0);
        cell.setCellValue("   ");
        cell = row.createCell(1);
        cell.setCellValue("  ");

        //   ,      ,               ,      ,     。              
        List users = getUsers();
        for (int i = 0; i < users.size(); i++) {
            HSSFRow row1 = sheet.createRow(i + 1);
            User user = users.get(i);
            //       
            row1.createCell(0).setCellValue(user.getUsername());
            row1.createCell(1).setCellValue(user.getPassword());
        }

        File file = new File("D:/user1.xls");
    	if (file.exists()) {
    		file.delete();
    	}
        //           
        try {
            file.createNewFile();
            workbook.write(file);
            System.out.println("    ");
            workbook.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

ここではただの簡単な実装で、上のコードを理解すれば、需要がどのように変更されても、百変はそこから離れません!