POI export data to Excel file


import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.net.URLEncoder;
import java.text.DecimalFormat;
import java.util.List;


import javax.servlet.http.HttpServletResponse;


import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFPalette;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddress;


/**
 * @author 夏世雄E-mail:[email protected]
 * @version Creation time: 2018 12:09:53 PM, March 22, 2015 POI export excel file tool class
 */
public class PoiExcelExport {
HttpServletResponse response;
// file name
private String fileName;
// file save path
private String fileDir;
// sheet name
private String sheetName ;
// Header font
private String titleFontType = "Arial";
// Header background color
private String titleBackColor = "C1FBEE";
// Header font size
private short titleFontSize = 12;
// Add auto-filtered columns such as A:M
private String address = "";
// text font
private String contentFontType = "Arial";
//
positive text number private short contentFontSize = 12;
// decimal places of Float type data
private String floatDecimal = ".00";
// Double type data Decimal place
private String doubleDecimal = ".00";
// Set the column formula
private String colFormula[] = null;


DecimalFormat floatDecimalFormat = new DecimalFormat(floatDecimal);
DecimalFormat doubleDecimalFormat = new DecimalFormat(doubleDecimal);


private HSSFWorkbook workbook = null;


public PoiExcelExport(String fileDir, String sheetName) {
this.fileDir = fileDir;
this.sheetName = sheetName;
workbook = new HSSFWorkbook();
}


public PoiExcelExport(HttpServletResponse response, String fileName, String sheetName) {
this.response = response;
this.fileName = fileName;
this.sheetName = sheetName;
workbook = new HSSFWorkbook();
}


/**
* 设置表头字体.

* @param titleFontType
*/
public void setTitleFontType(String titleFontType) {
this.titleFontType = titleFontType;
}


/**
* 设置表头背景色.

* @param titleBackColor 十六进制
*/
public void setTitleBackColor(String titleBackColor) {
this.titleBackColor = titleBackColor;
}


/**
* Set the header font size.

* @param titleFontSize
*/
public void setTitleFontSize(short titleFontSize) {
this.titleFontSize = titleFontSize;
}


/**
* Set the header to automatically filter the field , Such as A:AC.

* @param address
*/
public void setAddress(String address) {
this.address = address;
}


/**
* Set the body font.

* @param contentFontType
*/
public void setContentFontType(String contentFontType) {
this.contentFontType = contentFontType;
}


/**
* Set the positive text number.

* @param contentFontSize
*/
public void setContentFontSize(short contentFontSize) {
this.contentFontSize = contentFontSize;
}


/**
* Set the float type data decimal place default. 00

* @param doubleDecimal such as ".00"
*/
public void setDoubleDecimal(String doubleDecimal) {
this.doubleDecimal = doubleDecimal;
}


/**
* Set doubel type data decimal place default. 00

* @param floatDecimalFormat such as ".00
*/
public void setFloatDecimalFormat(DecimalFormat floatDecimalFormat) {
this .floatDecimalFormat = floatDecimalFormat;
}


/**
* Set the column formula

* @param colFormula Store the row number involved in the i-1 column formula with @Replace such as A@+B@
*/
public void setColFormula(String[] colFormula) {
this.colFormula = colFormula;
}


/**
* Write excel.

* @param titleColumn corresponds to the attribute name of the bean
* @param titleName excel to export the table name
* @param titleSize column width
* @param dataList data
*/
public void wirteExcel(String titleColumn[], String titleName[], int titleSize[],
List<?> dataList) {
// Add Worksheet (xls file generated when no sheet is added will report an error when opened)
Sheet sheet = workbook.createSheet(this.sheetName);
// New file
OutputStream out = null;
try {
if (fileDir != null) {
// There is a file path, save it locally
out = new FileOutputStream(fileDir);
} else {
// Otherwise, write directly to the output stream
out = response.getOutputStream();
fileName = fileName + ".xls";
response.setContentType("application/x-msdownload");
response.setHeader("Content-Disposition",
"attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
}


// Write the header of excel
Row titleNameRow = workbook.getSheet(sheetName).createRow(0);
// Set the style
HSSFCellStyle titleStyle = workbook.createCellStyle();
titleStyle = (HSSFCellStyle) setFontAndBorder(titleStyle, titleFontType,
(short) titleFontSize);
titleStyle = (HSSFCellStyle) setColor(titleStyle, titleBackColor, (short) 10);


for (int i = 0; i <titleName.length; i++) {
sheet.setColumnWidth(i, titleSize[i] * 256); // Set Width
Cell cell = titleNameRow.createCell(i);
cell.setCellStyle(titleStyle);
cell.setCellValue(titleName[i].toString());
}


// Add automatic filtering to the header
if (!"".equals(address )) {
CellRangeAddress c = (CellRangeAddress) CellRangeAddress.valueOf(address);
sheet.setAutoFilter(c);
}


// Get data through reflection and write it to excel
if (dataList != null && dataList.size()> 0 ) {
// Set the style
HSSFCellStyle dataStyle = workbook.createCellStyle();
titleStyle = (HSSFCellStyle) setFontAndBorder(titleStyle, contentFontType,
(short) contentFontSize);


if (titleColumn.length> 0) {
for (int rowIndex = 1; rowIndex <= dataList.size(); rowIndex++) {
Object obj = dataList. get(rowIndex-1); // Obtain the object
Class clsss = obj.getClass(); // Obtain the class instance of the pair of objects
Row dataRow = workbook.getSheet(sheetName).createRow(rowIndex);
for (int columnIndex = 0; columnIndex <titleColumn.length; columnIndex++) {
String title = titleColumn[columnIndex].toString().trim();
if (!"".equals(title)) {// The field is not empty
// Make the first letter Uppercase
String UTitle = Character.toUpperCase(title.charAt(0))
+ title.substring(1, title.length()); // Make the first letter uppercase;
String methodName = "get" + UTitle;


// 设置要执行的方法
Method method = clsss.getDeclaredMethod(methodName);


// 获取返回类型
String returnType = method.getReturnType().getName();


String data = method.invoke(obj) == null ? ""
: method.invoke(obj).toString();
Cell cell = dataRow.createCell(columnIndex);
if (data != null && !"".equals(data)) {
if ("int".equals(returnType)) {
cell.setCellValue(Integer.parseInt(data));
} else if ("long".equals(returnType)) {
cell.setCellValue(Long.parseLong(data));
} else if ("float".equals(returnType)) {
cell.setCellValue(
floatDecimalFormat.format(Float.parseFloat(data)));
} else if ("double".equals(returnType)) {
cell.setCellValue(doubleDecimalFormat
.format(Double.parseDouble(data)));
} else {
cell.setCellValue(data);
}
}
} else { // 字段为空 检查该列是否是公式
if (colFormula != null) {
String sixBuf = colFormula[columnIndex].replace("@",
(rowIndex + 1) + "");
Cell cell = dataRow.createCell(columnIndex);
cell.setCellFormula(sixBuf.toString());
}
}
}
}


}
}


workbook.write(out);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}


/**
* Write the hexadecimal color code into the style to set the color

* @param style to ensure uniform style
* @param color color: 66FFDD
* @param index index 8-64 cannot be repeated when used
* @return
*/
public CellStyle setColor(CellStyle style, String color, short index) {
if (color != "" && color != null) {
// Convert to RGB code
int r = Integer.parseInt((color.substring(0, 2)), 16); // convert to hexadecimal
int g = Integer.parseInt((color.substring(2, 4)), 16);
int b = Integer.parseInt((color.substring(4, 6)), 16);
// Custom cell color
HSSFPalette palette = workbook.getCustomPalette();
palette.setColorAtIndex((short) index, (byte) r, (byte) g, (byte) b);


style.setFillPattern(CellStyle.SOLID_FOREGROUND);
style.setFillForegroundColor(index);
}
return style;
}


/**
* 设置字体并加外边框

* @param style 样式
* @param style 字体名
* @param style 大小
* @return
*/
public CellStyle setFontAndBorder(CellStyle style, String fontName, short size) {
HSSFFont font = workbook.createFont();
font.setFontHeightInPoints(size);
font.setFontName(fontName);
// font.setBold(true);
style.setFont(font);
style.setBorderBottom(CellStyle.BORDER_THIN); // Bottom border
style.setBorderLeft(CellStyle.BORDER_THIN); // Left border
style.setBorderTop(CellStyle.BORDER_THIN); // Upper border
style.setBorderRight(CellStyle.BORDER_THIN);// Right border
return style;
}


/**
* Delete file

* @param fileDir
* @return
*/
public boolean deleteExcel() {
boolean flag = false;
File file = new File(this.fileDir);
// Determine the directory or file whether there are
(! file.exists ()) if { // there is no return false
return Flag;
} the else {
// determine whether the file
if (file.isFile ()) {// call the method to delete the file when the file
file. delete();
flag = true;
}
}
return flag;
}

}




//service layer usage example
public boolean exportList (HttpServletResponse response) {


     //Set excle header
   String[] headers = new String[] {"Record ID","User ID","User name ","Exchange Item Name","Consumption Points","Specifications","Exchange Quantity","Remarks","Exchange Status","Exchange Time","Processing Status","Operation"};
   //Set the requirements Display the attribute name of the pojo corresponding to each column of the data
 String titleColumn[]={"id", "mobile", "realityname","commodity","reduceintegral","types","exNumber","remarks","reducetype ","time","state","flag"};   
  //Set the column width
  int titleSize[] = {13,13,13,30,13, 13,13,30,13,20,13,13};

    //Data of the database query to be exported

   List<Object>  showExcleList = someService.findSomeList();

   //Table Name

 String fileName = "Commodity Exchange Statistics Table";

  String sheetName = "Commodity exchange";
  //Create export tool class, file name and sheet name
  PoiExcelExport pee = new PoiExcelExport(response, fileName, sheetName);
          try {
//Call  
pee.wirteExcel(titleColumn, headers, titleSize, showExcleList);
logger.error("Export the list successfully");
return true;


} catch (Exception e) { e.printStackTrace(); logger.error("Export the list failed"); return false; } }





Guess you like

Origin blog.csdn.net/qq_37451441/article/details/80089289