您的位置:首页 > 编程语言 > Java开发

Java使用POI将数据导出到Excel的工具方法

2014-12-05 15:32 1051 查看
最近需要将数据库中的数据导出,生成一个Excel文档。想来想去还是使用Apache的OPI写了一个工具方法。

工具方法的代码如下:

package com.zlc.scsis.export.excel;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.RichTextString;

public class ExportExcel4ServerUtil
{

/**
* @MethodName createExcel
* @Description 根据工作薄名称和列名创建Excel表格,该方法适用于创建一个Excel表格中有多个工作薄的需求
*
* @author laosan
* @date 2014-12-4 下午04:15:58
* @param sheetNames
*            Excel中每个sheet的名字。参数的长度就是创建sheet的个数。
* @param eachSheetColumnTitles
*            每个sheet每列的标题。参数中的Key值就是sheet的名字,即在Map中的对应关系为
*            "sheet名称 --> 该sheet的列标题" ,且列标题的个数就是该sheet的列数。
* @return
*/
public static HSSFWorkbook createExcel4MoreSheet(Set<String> sheetNames,
Map<String, List<String>> eachSheetColumnTitles)
{
// 如果传入的工作薄名称为空,返回空
if (null == sheetNames || sheetNames.isEmpty())
{
return null;
}

// 创建一个Excel表格
HSSFWorkbook workbook = new HSSFWorkbook();

// 在Excel表格中创建工作薄,并设置列标题
for (String sheetName : sheetNames)
{

// 在Excel文件中创建一个工作薄
HSSFSheet sheet = workbook.createSheet(sheetName);

// 列标题参数为空,表示工作薄不需要列标题
if (null == eachSheetColumnTitles || eachSheetColumnTitles.isEmpty())
{
continue;
}

// 获取工作薄名称对应的列标题
List<String> columnTitelsList = eachSheetColumnTitles.get(sheetName);

// 如果工作薄名称对应的列标题为空,不再处理这个工作薄,处理下一个
if (null == columnTitelsList || columnTitelsList.isEmpty())
{
continue;
}

// 在工作薄中创建一行,改行用于列标题
HSSFRow columnTitle = sheet.createRow(0);

// 在行中创建列,并设置列标题
for (int i = 0; i < columnTitelsList.size(); i++)
{
createCell(columnTitle, (short) i, columnTitelsList.get(i)).setCellStyle(
createDefaultCellStyle(workbook));
}
}

return workbook;
}

/**
* @MethodName createExcel
* @Description 创建一个Excel表格,该方法只适用于创建一个Excel表格中只有一个工作薄的情况
*
* @author laosan
* @date 2014-12-5 上午09:12:07
* @param sheetName
*            工作薄名称,可以为空,如果为空工作薄名称为默认值
* @param columnTitelList
*            列标题列表, 可以为空,如果为空表示不创建列标题
* @return
*/
public static HSSFWorkbook createExcel(String sheetName, List<String> columnTitelList)
{

// 创建一个Excel表格
HSSFWorkbook workbook = new HSSFWorkbook();

// 在Excel文件中创建一个工作薄
HSSFSheet sheet = null;
if (null == sheetName || sheetName.trim().length() == 0)
{
sheet = workbook.createSheet();
}
else
{
sheet = workbook.createSheet(sheetName);
}

// 如果传入的列标题列表为空,表示不需要创建列标题
if (null == columnTitelList || columnTitelList.isEmpty())
{
return workbook;
}

// 在工作薄中创建一行,该行用于列标题
HSSFRow columnTitle = sheet.createRow(0);

// 冻结首行,标题行
sheet.createFreezePane(0, 1);

// 在行中创建列,并设置列标题
for (int i = 0; i < columnTitelList.size(); i++)
{
createCell(columnTitle, (short) i, columnTitelList.get(i)).setCellStyle(
createDefaultCellStyle(workbook));
}

return workbook;
}

/**
* @MethodName createDefaultCellStyle
* @Description 创建单元格的默认格式。左右居中、上下居中、自动换行。
*
* @author laosan
* @date 2014-12-5 上午10:48:07
* @param workbook
*            Excel表格对象
* @return
*/
public static HSSFCellStyle createDefaultCellStyle(HSSFWorkbook workbook)
{
// 如果传入的Excel对象为空,返回空
if (null == workbook)
{
return null;
}

// 创建单元格样式
HSSFCellStyle cellStyle = workbook.createCellStyle();

// 指定单元格居中对齐
cellStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);

// 指定单元格垂直居中对齐
cellStyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

// 指定当单元格内容显示不下时自动换行
cellStyle.setWrapText(true);

return cellStyle;
}

/**
* @MethodName createCell
* @Description 创建一个单元格
*
* @author laosan
* @date 2014-12-5 上午11:11:09
* @param row
* @param column
* @param cellValue
* @return
*/
@SuppressWarnings("deprecation")
public static HSSFCell createCell(HSSFRow row, short column, String cellValue)
{
// 如果传入的行对象为空,直接返回null
if (null == row)
{
return null;
}

// 创建一个单元格
HSSFCell cell = row.createCell(column);

// 如果传入的值为空,显示空白单元格
if (null == cellValue || cellValue.trim().length() == 0)
{
cell.setCellValue("");
return cell;
}

// 判断值中是否含有中文,如果有中文设置单元格类型
Pattern pat = Pattern.compile("[\u4e00-\u9fa5]");
Matcher matcher = pat.matcher(cellValue);

if (matcher.find())
{
cell.setCellType(HSSFCell.ENCODING_UTF_16);
cell.setCellValue(cellValue);
}
else
{
cell.setCellValue(cellValue);
}

return cell;
}

/**
* @MethodName createCell
* @Description 创建一个单元格
*
* @author laosan
* @date 2014-12-5 下午02:10:30
* @param row
* @param column
* @param cellValue
* @return
*/
@SuppressWarnings("deprecation")
public static HSSFCell createCell(HSSFRow row, short column, double cellValue)
{
if (null == row)
{
return null;
}

HSSFCell cell = row.createCell(column);
cell.setCellValue(cellValue);
return cell;
}

/**
* @MethodName createCell
* @Description 创建一个单元格
*
* @author laosan
* @date 2014-12-5 下午02:11:02
* @param row
* @param column
* @param cellValue
* @return
*/
@SuppressWarnings("deprecation")
public static HSSFCell createCell(HSSFRow row, short column, boolean cellValue)
{
if (null == row)
{
return null;
}

HSSFCell cell = row.createCell(column);
cell.setCellValue(cellValue);
return cell;
}

/**
* @MethodName createCell
* @Description 创建一个单元格
*
* @author laosan
* @date 2014-12-5 下午02:11:42
* @param row
* @param column
* @param cellValue
* @return
*/
@SuppressWarnings("deprecation")
public static HSSFCell createCell(HSSFRow row, short column, RichTextString cellValue)
{
if (null == row)
{
return null;
}

HSSFCell cell = row.createCell(column);
cell.setCellValue(cellValue);
return cell;
}

/**
* @MethodName createCell
* @Description 创建一个单元格
*
* @author laosan
* @date 2014-12-5 下午02:11:57
* @param row
* @param column
* @param date
* @param workbook
* @param dateFormat
* @return
*/
@SuppressWarnings("deprecation")
public static HSSFCell createCell(HSSFRow row, short column, Date date, HSSFWorkbook workbook,
String dateFormat)
{
if (null == row)
{
return null;
}

// 创建一个单元格
HSSFCell cell = row.createCell(column);

// 传入的参数值为空,显示空白单元格
if (null == date)
{
cell.setCellValue("");
return cell;
}

HSSFDataFormat format = workbook.createDataFormat();

// 创建单元格样式
HSSFCellStyle cellStyle = createDefaultCellStyle(workbook);

// 设置日期的显示格式
cellStyle.setDataFormat(format.getFormat(dateFormat));

cell.setCellValue(date);
cell.setCellStyle(cellStyle);

return cell;
}

/**
* @MethodName createCell
* @Description 创建一个单元格
*
* @author laosan
* @date 2014-12-5 下午02:12:11
* @param row
* @param column
* @param calendar
* @param workbook
* @param dateFormat
* @return
*/
@SuppressWarnings("deprecation")
public static HSSFCell createCell(HSSFRow row, short column, Calendar calendar,
HSSFWorkbook workbook, String dateFormat)
{
if (null == row)
{
return null;
}

// 创建一个单元格
HSSFCell cell = row.createCell(column);

// 传入的参数值为空, 显示空白单元格
if (null == calendar)
{
cell.setCellValue("");
return cell;
}

HSSFDataFormat format = workbook.createDataFormat();

// 创建单元格样式
HSSFCellStyle cellStyle = createDefaultCellStyle(workbook);

// 设置日期的显示格式
cellStyle.setDataFormat(format.getFormat(dateFormat));

cell.setCellValue(calendar);
cell.setCellStyle(cellStyle);
return cell;
}

/**
* @MethodName createCell
* @Description 创建一个单元格
*
* @author laosan
* @date 2014-12-10 下午3:02:51
* @param row
* @param column
* @param cellValue
* @return
*/
public static HSSFCell createCell(HSSFRow row, short column, Integer cellValue)
{
if (row == null)
{
return null;
}

if (null == cellValue)
{
return createCell(row, column, "");
}

return createCell(row, column, cellValue.toString());
}

/**
* @MethodName createCell
* @Description 创建一个单元格
*
* @author laosan
* @date 2014-12-10 下午3:05:01
* @param row
* @param column
* @param cellValue
* @return
*/
public static HSSFCell createCell(HSSFRow row, short column, Long cellValue)
{
if (row == null)
{
return null;
}

if (null == cellValue)
{
return createCell(row, column, "");
}

return createCell(row, column, cellValue.toString());
}

/**
* @MethodName createCell
* @Description 创建一个单元格
*
* @author laosan
* @date 2014-12-10 下午3:04:18
* @param row
* @param column
* @param cellValue
* @return
*/
public static HSSFCell createCell(HSSFRow row, short column, Double cellValue)
{
if (row == null)
{
return null;
}

if (null == cellValue)
{
return createCell(row, column, "");
}

return createCell(row, column, cellValue.toString());
}

/**
* @MethodName exportExcel
* @Description 导出Excel文件到指定目录
*
* @author laosan
* @date 2014-12-4 下午04:26:50
* @param workbook
*            Excel对象
* @param pathAndName
*            Excel文件导出的路径和文件名,例如:"C:\\Test.xls"。
* @throws IOException
*/
public static void exportExcel(HSSFWorkbook workbook, String pathAndName) throws IOException
{
// 文件输出IO流
FileOutputStream fos = null;

try
{
fos = new FileOutputStream(new File(pathAndName));

// 文件导出
workbook.write(fos);
}
catch (FileNotFoundException e)
{
throw new FileNotFoundException(e.getMessage());
}
catch (IOException e)
{
throw new IOException(e);
}
finally
{
// 关闭IO流
fos.close();
}
}

}


下面是测试的代码:

package com.export.excel;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

public class Test {
public static void main(String[] args) {
//		Set<String> sheetNames = new HashSet<String>();
//		sheetNames.add("统计B");
//		sheetNames.add("统计A");
//		sheetNames.add("统计1");
//
//		Map<String, List<String>> eachSheetColumnTitles = new HashMap<String, List<String>>();
//		List<String> columnTitles1 = new ArrayList<String>();
//		columnTitles1.add("统计A-3");
//		columnTitles1.add("统计A-1");
//		columnTitles1.add("统计A-2");
//		eachSheetColumnTitles.put("统计A", columnTitles1);
//
//		List<String> columnTitles2 = new ArrayList<String>();
//		columnTitles2.add("统计B-2");
//		columnTitles2.add("统计B-1");
//		columnTitles2.add("统计B-3");
//		eachSheetColumnTitles.put("统计B", columnTitles2);
//
//		HSSFWorkbook workbook = ExportExcel4ServerUtil.createExcel4MoreSheet(sheetNames,
//				eachSheetColumnTitles);

List<String> columnTitelList = new ArrayList<String>();

columnTitelList.add("第一列");
columnTitelList.add("第二列");
columnTitelList.add("第三列");
columnTitelList.add("第四列");

HSSFWorkbook workbook = ExportExcel4ServerUtil.createExcel("测试", columnTitelList);

HSSFCellStyle cellStyle = ExportExcel4ServerUtil.createDefaultCellStyle(workbook);

HSSFSheet sheet = workbook.getSheet("测试");

HSSFRow row = sheet.createRow((short)1);

ExportExcel4ServerUtil.createCell(row, (short)0, 200).setCellStyle(cellStyle);
ExportExcel4ServerUtil.createCell(row, (short)1, "汉子").setCellStyle(cellStyle);
ExportExcel4ServerUtil.createCell(row, (short)2, new Date(), workbook, "yyyy-MM-dd");
ExportExcel4ServerUtil.createCell(row, (short)3, Calendar.getInstance(), workbook, "MM-dd-yyyy");

try {
ExportExcel4ServerUtil.exportExcel(workbook, D:" + File.separator + "测试.xls");
} catch (IOException e) {
e.printStackTrace();
}
}
}


方法只是简单的测试了一下,具体行不行还要放到项目里面试试才知道。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: