生成excel文件代码:
package exceldemo;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
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.ss.usermodel.WorkbookFactory;
public class ExcelDemo {
//判断并获取每个cell
public static Object getCellFormatValue(Cell cell) {
Object cellValue = null;
if(cell != null) {
switch (cell.getCellType()) {
case Cell.CELL_TYPE_NUMERIC:{
cellValue = String.valueOf(cell.getNumericCellValue());
break;
}
case Cell.CELL_TYPE_FORMULA:{
if(DateUtil.isCellDateFormatted(cell)) {
cellValue = cell.getDateCellValue();
} else {
cellValue = String.valueOf(cell.getNumericCellValue());
}
}
case Cell.CELL_TYPE_STRING:{
cellValue = cell.getRichStringCellValue().getString();
break;
}
default:
cellValue = "";
break;
}
} else {
cellValue = "";
}
return cellValue;
}
public static void main(String[] args) {
File file = new File("C:\\Users\\ThinkPad\\Desktop\\1.xls");
try {
Workbook wb = WorkbookFactory.create(new FileInputStream(file));
Sheet sheet = null;
Row row = null;
if(wb != null) {
sheet = wb.getSheetAt(0);
int rownum = sheet.getPhysicalNumberOfRows();//获取行数
List<ExcelDemoBean> list = new ArrayList<ExcelDemoBean>();
for (int i = 0; i < rownum; i++) {
row = sheet.getRow(i);
if(row != null) {
ExcelDemoBean bean = new ExcelDemoBean();
bean.setCell1((String) ExcelDemo.getCellFormatValue(row.getCell(0)));
bean.setCell2((String) ExcelDemo.getCellFormatValue(row.getCell(1)));
bean.setCell3((String) ExcelDemo.getCellFormatValue(row.getCell(2)));
list.add(bean);
} else {
break;
}
}
System.out.println(list);
}
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
bean文件:
package exceldemo;
public class ExcelDemoBean {
private String cell1;
private String cell2;
private String cell3;
public String getCell1() {
return cell1;
}
public void setCell1(String cell1) {
this.cell1 = cell1;
}
public String getCell2() {
return cell2;
}
public void setCell2(String cell2) {
this.cell2 = cell2;
}
public String getCell3() {
return cell3;
}
public void setCell3(String cell3) {
this.cell3 = cell3;
}
@Override
public String toString() {
return "ExcelDemoBean [cell1=" + cell1 + ", cell2=" + cell2 + ", cell3=" + cell3 + "]";
}
}
用到的jar包:
poi-3.9.jar、poi-ooxml-3.9.jar
链接:https://pan.baidu.com/s/14IaNp4a5-O-MVOz5TijRxQ
提取码:cb2r
复制这段内容后打开百度网盘手机App,操作更方便哦
java生成excel文件可以看这位博主写的:https://blog.csdn.net/chenssy/article/details/8759840
如果HSSHWorkbook、HSSFSheet、HSSFRow、HSSFCell无法满足的话可以使用XSSFWorkbook、XSSFSheet、XSSFRow、XSSFCell