这段代码是我在网上看到别人写的,而后稍做修改,添加了部分注释,从新在放到这上面,但愿对你们有帮助
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.DataFormat;
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.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
/**
*
@author xxx
*/
public class CreateSimpleExcelToDisk {
/**
* @param args
*/
public static void main(String[] args) throws Exception {
// 导出xls格式的excel
// Workbook wb = new HSSFWorkbook();
// 导出xlsx格式的excel
Workbook wb = new XSSFWorkbook();
DataFormat format = wb.createDataFormat();
CellStyle style;
// 建立一个SHEET
Sheet sheet1 = wb.createSheet("产品清单");
// 设置表头要显示的内容
String[] title = {"编号", "产品名称", "产品价格", "产品数量", "生产日期", "产地", "是否出口"};
int i = 0;
// 建立一行
Row row = sheet1.createRow((short) 0);
// 填充标题.将标题放入第一行各列
for (String s : title) {
Cell cell = row.createCell(i);
cell.setCellValue(s);
i++;
}
// 建立第二行
Row row1 = sheet1.createRow((short) 1);
// 填充第二行第一列数据
row1.createCell(0).setCellValue(20071001);
// 填充第二行第二列数据
// row1.createCell(1).setCellValue("金鸽瓜子");
// 建立一个单元格子
Cell cell2 = row1.createCell(2);
// 填充产品价格
cell2.setCellValue(2.45);
style = wb.createCellStyle();
style.setDataFormat(format.getFormat("#.##"));
// 设定样式
cell2.setCellStyle(style);
// 填充产品数量
row1.createCell(3).setCellValue(200);
/*
* 定义显示日期的公共格式
* 如:yyyy-MM-dd hh:mm
*/
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String newdate = sdf.format(new Date());
// 填充出产日期
row1.createCell(4).setCellValue(newdate);
row1.createCell(5).setCellValue("陕西西安");
// 显示布尔值
row1.createCell(6).setCellValue(true);
// 合并第二行第一列和第二列,此时value值为“金鸽瓜子的那一列要被注释掉”
row1.getSheet().addMergedRegion(new CellRangeAddress(1, 1, 0, 1));
Row row2 = sheet1.createRow((short) 2);
Cell cell3 = row2.createCell((short) 0);
cell3.setCellValue("合并了三个单元格");
// 真正合并的操做在这一句,起始行,结束行,起始列,结束列
row2.getSheet().addMergedRegion(new CellRangeAddress(2, 2, 0, 2));
FileOutputStream fileOut = new FileOutputStream("E:\\test.xlsx");
wb.write(fileOut);
fileOut.close();
}
} java
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-examples</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1-b04</version>
</dependency> apache