一、maven配置
<!--jxl-->
<dependency>
<groupId>net.sourceforge.jexcelapi</groupId>
<artifactId>jxl</artifactId>
<version>2.6.12</version>
</dependency>
二、工具类方法
package util2;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import java.io.File;
public class ExecelBean2 {
private WritableWorkbook workbookA;
private WritableSheet sheetA;
private int colNum = 1;
public ExecelBean2(String filePath, String sheetName, String[] titleArray){
//创建Excel文件
File fileA = new File(filePath);
if(fileA.exists()){
//如果文件存在就删除
fileA.delete();
}
try {
fileA.createNewFile();
//创建工作簿
workbookA = Workbook.createWorkbook(fileA);
sheetA = workbookA.createSheet(sheetName, 0);
writeCol(titleArray);
}catch (Exception e){
System.out.println("创建工作簿失败!请检查文件路径!程序无法继续执行!");
System.out.println(e);
System.exit(1);
}
}
private void writeCol(String[] titleArray){
//开始写入excel,创建模型文件头
try {
Label labelA = null;
//设置列名
for (int i = 0; i < titleArray.length; i++) {
labelA = new Label(i, 0, titleArray[i]);
sheetA.addCell(labelA);
}
}catch (Exception e){
System.out.println("fail");
}
}
public void writeExcel(String[] strs){
try {
Label labelA = null;
//获取数据源
for (int i = 0; i < strs.length; i++) {
//第0列,第1行
//然后就是第2行
labelA = new Label(i,colNum,strs[i]);
sheetA.addCell(labelA);
}
colNum++;
} catch (Exception e) {
System.out.println("addCell失败!");
System.out.println(e);
}
}
public void close(){
try {
workbookA.write(); //写入数据
workbookA.close(); //关闭连接
System.out.println("成功写入文件,请前往E盘查看文件!");
} catch (Exception e) {
System.out.println("文件write()失败!");
System.out.println(e);
}
}
}
其中,ExecelBean2是构造方法,传入文件名、sheet名、第一行的数组(当列名用),就会在本地创建xls文件;
writeCol是私有方法,就是创建第一行列名用的;
writeExcel方法接受的是数组,每行的;如果创建一行,colNum标志位就会移动到下一行;
close方法是关闭方法,当写完excel后,就调用这个方法关闭。
三、调用方法
public class Main {
public static void main(String[] args) {
String filePath = "E:/TestFile.xls";
String sheetName = "test1";
String[] titleArray = {"ID","姓名","地址","电话"};
//输入文件路径
ExecelBean2 execelBean = new ExecelBean2(filePath, sheetName, titleArray);
String[] row1 = {"1","a","china","12312341234"};
String[] row2 = {"2","b","china","12312341234"};
String[] row3 = {"3","c","china","12312341234"};
execelBean.writeExcel(row1);
execelBean.writeExcel(row2);
execelBean.writeExcel(row3);
execelBean.close();
}
}
创建ExcelBean2对象后,调用一次writeExcel方法,就写入一行数据;都写完后,调用close方法关闭即可。