package com.suning.crawler.util;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
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;
/**
* 将数据导出Excel
*
* @author xxx
*/
public class ExcelWrite
{
// 日志记录
private Logger logger = Logger.getLogger(ExcelWrite.class);
/**
* 标题行
*/
private List<String> title;
/**
* 构造函数
*
* @param titles 标题,用","分隔
*/
public ExcelWrite(String titles)
{
title = new ArrayList<String>();
// 标题
if (null != titles)
{
for (String titleName : titles.split(","))
{
title.add(titleName);
}
}
}
/**
* 构造函数
*
* @param title 标题
*/
public ExcelWrite(List<String> title)
{
this.title = title;
}
/**
* 将数据信息写入Excel文件
*
* @param datas 数据信息
* @param fileName 文件名称
* @param filePath 导出文件路径,默认路径是output
*/
public void WriteData(List<List<String>> datas, String fileName, String filePath)
{
// 目录
File dir = new File(filePath);
if (!dir.exists())
{
dir.mkdirs();
}
// 创建文件
File file = new File(filePath + fileName);
WriteData(datas, file);
}
/**
* 将数据信息写入Excel文件
*
* @param datas 数据信息
* @param file 文件
*/
public void WriteData(List<List<String>> datas, File file)
{
String sheetName = file.getName();
sheetName = sheetName.substring(0, sheetName.lastIndexOf("."));
WritableWorkbook wb = null;
try
{
// 打开文件
wb = Workbook.createWorkbook(file);
WritableSheet sheet = wb.createSheet(sheetName, 0);
// 创建标题
Label[] titleLabels = getLabel(0, title);
for (Label label : titleLabels)
{
sheet.addCell(label);
}
// 把内容写入文件中
int index = 0;
if (null != title && !title.isEmpty())
{
index = 1;
}
for (List<String> record : datas)
{
Label[] productLabels = getLabel(index, record);
for (Label label : productLabels)
{
sheet.addCell(label);
}
++index;
}
wb.write();
}
catch (RowsExceededException e)
{
logger.error("Exception is happened when jxl write rows is exceeded.", e);
}
catch (WriteException e)
{
logger.error("Write the file exception", e);
}
catch (IOException e)
{
logger.error("write the file fails", e);
}
catch (Exception e)
{
logger.error("other exception", e);
}
finally
{
// 关闭写
if (null != wb)
{
try
{
wb.close();
}
catch (WriteException e)
{
logger.error("write the file fails", e);
}
catch (IOException e)
{
logger.error("write the file fails", e);
}
}
}
}
/**
* 将商品信息封装成Excel列
*
* @param row Excel行
* @param datas 数据信息
* @return 数据信息对应的列
*/
private Label[] getLabel(int row, List<String> datas)
{
Label[] label = new Label[datas.size()];
for (int i = 0; i < datas.size(); i++)
{
label[i] = new Label(i, row, datas.get(i));
}
return label;
}
}
Excel 写入(jxl)
猜你喜欢
转载自spacecity.iteye.com/blog/1465282
今日推荐
周排行