import java.io.File;
import java.io.IOException;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;
import org.apache.log4j.Logger;
public class ExcelUtils {
static private Logger logger = Logger.getLogger(ExcelUtils.class);
static public int SUCCESS = 0;
static public int ERROR = -1;
/**
* 创建单个sheet的excel文件,自己指定路径,用二维数组来映射相应的单元格
**/
static public int createExcel(String fileRootPath,String fileName,String sheetName,String[][] dataArr){
int result = ERROR;
try {
if(fileRootPath == null || "".equals(fileRootPath) || fileName == null || "".equals(fileName) ){
throw new Exception("创建excel文件错误:createExcel方法参数值为空!");
}
if(dataArr == null || dataArr[0] == null){
throw new Exception("输入的参数dataArr错误!");
}
String filePath = fileRootPath + fileName;
File file = new File(fileRootPath);
if(!file.exists()){
file.mkdirs();
}
WritableWorkbook book = Workbook.createWorkbook(new File(filePath));
if(sheetName == null || "".equals(sheetName)){
sheetName = "第一页";
}
// 生成名为sheetName的工作表,参数0表示这是第一页
WritableSheet sheet = book.createSheet(sheetName , 0);
// 在Label对象的构造子中指名单元格位置是第一列第一行(0,0)
// 以及单元格内容为test
for(int i=0 ;i<dataArr.length;i++){
for(int j=0;j<dataArr[0].length;j++){
Label label = new Label(j, i, dataArr[i][j]);
sheet.addCell(label);// 将定义好的单元格添加到工作表中
}
}
book.write();
book.close();
result = SUCCESS;
} catch (IOException e) {
logger.error("excel文件路径错误!");
logger.error(e.toString());
return result;
} catch (RowsExceededException e) {
logger.error("创建excel时,行超过!");
logger.error(e.toString());
return result;
} catch (WriteException e) {
logger.error("创建excel时,写入错误!");
logger.error(e.toString());
return result;
}catch (Exception e) {
logger.error(e.toString());
return result;
}
return result;
}
public static void main(String args[]) {
String[][] myarr = new String[2][3];
myarr[0][0]="11";
myarr[0][1]="12";
myarr[0][2]="13";
myarr[1][0]="21";
myarr[1][1]="22";
myarr[1][2]="23";
ExcelUtils.createExcel("D:/test/", "test.xls", "代理商账户列表", myarr);
}
}
java生成一个数据的excel横向纵向一起遍历 java生成excel表格
转载本文章为转载内容,我们尊重原作者对文章享有的著作权。如有内容错误或侵权问题,欢迎原作者联系我们进行内容更正或删除文章。
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章
-
接了个变态需求:生成 Excel + PDF 导出,用 Java 怎么实现?
接了个变态需求:生成 Excel + PDF 导出,用 Java 怎么实现?
List 表单 实体类 pdf springboot -
java导出Excel横向纵向遍历 java表格数据导出excel
目录一、技术选型 二、实现过程1、导入依赖2、编写工具类 EasyExcelUtil3、公用参数类 EasyExcelParams4、表格样式实体类 MyWriteHandler5、数据实体类(也是表头)BaseRowModel6、主程序7、运行程序,效果如下:8、导出的Excel效果一、技术选型 ava解析、生成Excel比较有名的框架有Apache po
java导出Excel横向纵向遍历 easyExcel 导出Excel 导出Excel样式设置 Java Web 下载Excel文件