Use poi to write objects to execl

package com.wz.poi;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
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;

public class WriteExcel {
private static final String EXCEL_XLS = "xls";
private static final String EXCEL_XLSX = "xlsx";

/**
*
* @param dataList data collection
* @param cloumnCount object attribute column number
* @param finalXlsxPath file path
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public static void writeExcel(List<Map> dataList , int cloumnCount,String finalXlsxPath){
OutputStream out = null;
try {
// Get the total number of columns
int columnNumCount = cloumnCount;
// Read Excel document
File finalXlsxFile = new File(finalXlsxPath);
Workbook workBook = getWorkbok(finalXlsxFile);
/ / sheet corresponds to a work page
Sheet sheet = workBook.getSheetAt(0);
/**
* delete the original data, except the attribute column
*/
int rowNumber = sheet.getLastRowNum(); // the first row starts from 0
System.out.println("The total number of rows in the original data, except the attribute column: " + rowNumber);
for (int i = 1; i <= rowNumber; i++) {
Row row = sheet.getRow(i);
sheet.removeRow( row);
}
// Create a file output stream, output the spreadsheet: this is a must, otherwise anything you do on the sheet will not work
out = new FileOutputStream(finalXlsxPath);
workBook.write(out);
Map map = dataList.get(0);
/**
* Write new data to Excel
*/
for (int j = 0; j < dataList.size(); j++) {
// Create a row: start from the second row, skip Attribute column
Row row = sheet.createRow(j + 1);
// Get the map collection to be inserted
Collection coll = map.values();
// Convert coll to Object array
Object[] objectList = new Object[coll.size ()];
coll.toArray(objectList);
// Traverse the array to import
for(int i = 0; i < objectList.length; i++) {
Object object = objectList[i];
System.out.println(object);
for (int k = 0; k <= columnNumCount; k++) {

// Get the property name list of the object
String[] fields = getFiledName(object);
// Loop through the property list
for(int x = 0;x < fields.length; x++) {
row.createCell(x).setCellValue(getFiledValueByName(fields [x], object).toString());
}
}
}

}
// Create a file output stream, ready to output a spreadsheet: this is a must, otherwise anything you do on the sheet won't work
out = new FileOutputStream( finalXlsxPath);
workBook.write(out);
} catch (Exception e) {
e.printStackTrace();
} finally{
try {
if(out != null){
out.flush();
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println("Data export successfully");
}

/**
* 判断Excel的版本,获取Workbook
* @param in
* @param filename
* @return
* @throws IOException
*/
public static Workbook getWorkbok(File file) throws IOException{
Workbook wb = null;
FileInputStream in = new FileInputStream(file);
if(file.getName().endsWith(EXCEL_XLS)){ //Excel 2003
wb = new HSSFWorkbook(in);
}else if(file.getName().endsWith(EXCEL_XLSX)){ // Excel 2007/2010
wb = new XSSFWorkbook(in);
}
return wb;
}

/** 
 * 根据属性名获取属性值 
 * 
*/
private static Object getFiledValueByName(String fieldName, Object o){
try {
String firstLetter = fieldName.substring(0,1).toUpperCase();
String getter = "get" + firstLetter + fieldName.substring(1);
Method method = o.getClass().getMethod(getter, new Class[]{});
Object value = method.invoke(o, new Object[]{});
return value;
} catch (Exception e) {
System.out.println(e.getMessage());
return null;
}
}

/**
* 获取属性名数组
*/
private static String[] getFiledName(Object o){
Field[] fields = o.getClass().getDeclaredFields();
String[] fieldNames = new String[fields.length];
for (int i = 0; i < fields.length; i++) {
fieldNames[i] = fields[i].getName();
}
return fieldNames;
}

// 简单的测试
/* @SuppressWarnings("unchecked")
public static void main(String[] args) {
Student stu = new Student(1, "王智", "男", "18", "java工程师");
Map map = new HashMap<>();
map.put("1", stu);
List<Map> dataList = new ArrayList<>();
dataList.add(map);
writeExcel(dataList,getFiledName(stu).length, "H:\\MyTest\\Java\\test3.xlsx");
}*/

}

 

It is still the jar package of the previous article, which also uses reflection, and continues the design pattern of java tomorrow.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324635491&siteId=291194637