Excel2007以上版本導出簡單實現
使用Apache POI導出Excel(.xlsx)
Excel <=2003 數據限制,行(65536)列(256)
Excel =2007 數據限制,行(1048576)列(16384)
Apache POI官方網站
Apache POI使用詳解
此代碼可直接運行
package exportexcel;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class BuildXLSX {
@SuppressWarnings("resource")
public static void main(String[] args) throws IOException {
SimpleDateFormat dateFormat = new SimpleDateFormat("YYYYMMDDhhmmss");
String now = dateFormat.format(new Date());
//導出文件路徑
String basePath = "C:/";
//文件名
String exportFileName = "數據_"+now+".xlsx";
String[] cellTitle = {"序號","姓名","學號","性別","入學日期"};
//需要導出的數據
List<String[]> dataList = new ArrayList<String[]>();
dataList.add(new String[]{"東邪","17232401001","男","2015年9月"});
dataList.add(new String[]{"西毒","17232401002","女","2016年9月"});
dataList.add(new String[]{"南帝","17232401003","男","2017年9月"});
dataList.add(new String[]{"北丐","17232401004","男","2015年9月"});
dataList.add(new String[]{"中神通","17232401005","女","2017年9月"});
// 聲明一個工作薄
XSSFWorkbook workBook = null;
workBook = new XSSFWorkbook();
// 生成一個表格
XSSFSheet sheet = workBook.createSheet();
workBook.setSheetName(0,"學生信息");
// 創建表格標題行 第一行
XSSFRow titleRow = sheet.createRow(0);
for(int i=0;i<cellTitle.length;i++){
titleRow.createCell(i).setCellValue(cellTitle[i]);
}
//插入需導出的數據
for(int i=0;i<dataList.size();i++){
XSSFRow row = sheet.createRow(i+1);
row.createCell(0).setCellValue(i+1);
row.createCell(1).setCellValue(dataList.get(i)[0]);
row.createCell(2).setCellValue(dataList.get(i)[1]);
row.createCell(3).setCellValue(dataList.get(i)[2]);
row.createCell(4).setCellValue(dataList.get(i)[3]);
}
File file = new File(basePath+exportFileName);
//文件輸出流
FileOutputStream outStream = new FileOutputStream(file);
workBook.write(outStream);
outStream.flush();
outStream.close();
System.out.println("導出2007文件成功!文件導出路徑:--"+basePath+exportFileName);
}
}
需要的jar包
poi-3.15.jar
poi-ooxml-3.15.jar
poi-ooxml-schemas-3.15.jar
commons-collections4-4.1.jar
xmlbeans-2.3.0.jar