下面为本地生成excel的例子,若需导出,则将文件输出流转为response输出流。
package excel;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import jxl.Workbook;
import jxl.format.UnderlineStyle;
import jxl.write.Colour;
import jxl.write.Label;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
public class WriteExcel {
public void writeExcel() throws Exception{
File file = new File("D:\\Sim\\Project\\Excel\\test2.xls");
if (!file.exists()) {
file.createNewFile();
}
OutputStream os = new FileOutputStream(file);// 取得输出流
WritableWorkbook wbook = Workbook.createWorkbook(os); // 建立excel文件
String tmptitle = "测试数据"; // 标题
WritableSheet wsheet = wbook.createSheet(tmptitle, 0); // sheet名称
// 设置excel标题
WritableFont wfont = new WritableFont(WritableFont.ARIAL, 16, WritableFont.BOLD, false,
UnderlineStyle.NO_UNDERLINE, Colour.BLACK);
WritableCellFormat wcfFC = new WritableCellFormat(wfont);
wcfFC.setBackground(Colour.AQUA);
wsheet.addCell(new Label(1, 0, tmptitle, wcfFC));
wfont = new jxl.write.WritableFont(WritableFont.ARIAL, 14, WritableFont.BOLD, false,
UnderlineStyle.NO_UNDERLINE, Colour.BLACK);
wcfFC = new WritableCellFormat(wfont);
// 开始生成主体内容
wsheet.addCell(new Label(0, 2, "姓名"));
wsheet.addCell(new Label(1, 2, "性别"));
wsheet.addCell(new Label(2, 2, "证件类型"));
wsheet.addCell(new Label(3, 2, "证件号码"));
wsheet.addCell(new Label(4, 2, "手机号"));
int count = 0;
for (int i=0;i<10;i++) {
wsheet.addCell(new Label(0, count + 3, "我是"+i+"号"));
wsheet.addCell(new Label(4, count + 3, "my phone is:"+i));
count++;
}
// 主体内容生成结束
wbook.write(); // 写入文件
wbook.close();
os.close(); // 关闭流
}
}
pom依赖:
<dependencies>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.9</version>
</dependency>
<!-- https://mvnrepository.com/artifact/net.sourceforge.jexcelapi/jxl -->
<dependency>
<groupId>net.sourceforge.jexcelapi</groupId>
<artifactId>jxl</artifactId>
<version>2.6</version>
</dependency>
</dependencies>
结果图:
new Label(0, 2, "姓名") 指 新建一格 A3 相当于直角坐标系的X/Y轴定位
x轴 数组对应关系为{0,1,2,3,.......,25} to {A,B,C,........,Z}
y轴 从也是从0开始