上篇文章学习了Java读取Excel文件,这篇文章接着来简单总结Java写入Excel,话不多说,看代码:
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
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.apache.poi.ss.usermodel.Cell;
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.xssf.usermodel.XSSFWorkbook;
import com.lmb.excel.bean.Employee;
/**
* 写入Excel文件的方法(写表头,写数据)
* @author lmb
* @date 2017-3-16
*
*/
public class WriteExcel {
/**
* 将List集合数据写入excel(单个sheet)
* @param filePath 文件路径
* @param excelTitle 文件表头
* @param employeeList 要写入的数据集合
* @param sheetName sheet名称
*/
public static void writeEmployeeListToExcel(String filePath,String[] excelTitle,List<Employee> employeeList,String sheetName){
System.out.println("开始写入文件>>>>>>>>>>>>");
Workbook workbook = null;
if (filePath.toLowerCase().endsWith("xls")) {//2003
workbook = new XSSFWorkbook();
}else if(filePath.toLowerCase().endsWith("xlsx")){//2007
workbook = new HSSFWorkbook();
}else{
// logger.debug("invalid file name,should be xls or xlsx");
}
//create sheet
Sheet s