从数据库导出excel数据
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.dbunit.database.AmbiguousTableNameException;
import org.dbunit.database.DatabaseConfig;
import org.dbunit.database.DatabaseConnection;
import org.dbunit.database.IDatabaseConnection;
import org.dbunit.database.QueryDataSet;
import org.dbunit.dataset.Column;
import org.dbunit.dataset.DataSetException;
import org.dbunit.dataset.IDataSet;
import org.dbunit.dataset.ITable;
import org.dbunit.dataset.ITableIterator;
import org.dbunit.dataset.ITableMetaData;
import org.dbunit.dataset.xml.FlatXmlDataSet;
import org.dbunit.ext.mysql.MySqlDataTypeFactory;
import com.sf.iec.common.util.DateUtil;
import com.sf.iec.common.util.PoiUtils;
public class ExportData2Excel {
private final static String FILENAME ="d://dbtest//";
/**
* @param args
*/
public static void main(String[] args) throws Exception {
Connection conn = null;
try {
// conn = new DataSource().getConnection();
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(
"jdbc:mysql://10.0.137.17:3306/cbt?autoReconnect=true&" +
"useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull" +
"&transformedBitIsBoolean=true",
"root", "123456");
IDatabaseConnection connection = new DatabaseConnection(conn);
DatabaseConfig config = connection.getConfig();
config.setProperty(DatabaseConfig.PROPERTY_DATATYPE_FACTORY, new MySqlDataTypeFactory());
QueryDataSet dataSet = new QueryDataSet(connection);
//将整个atd_expensesclass表里的数据导出到 xml文件里
Map<String, String> tableMap = new HashMap<String, String>();
tableMap.put("prc_sundry_changes", "");
//把需要的表数据从数据库导入到excel
exportExcelFromDataBase(connection, dataSet, tableMap);
} catch (Exception e) {
e.printStackTrace();
}
finally{
if(null != conn)
{
conn.close();
}
}
}
/**
* 按照表名导出多个EXCEL文件(sheet名为表名)
* @param connection
* @param dataSet
* @param tableMap
* @throws AmbiguousTableNameException
* @throws IOException
* @throws DataSetException
* @throws FileNotFoundException
*/
public static void exportExcelFromDataBase(IDatabaseConnection connection, QueryDataSet dataSet,
Map<String, String> tableMap) throws AmbiguousTableNameException, IOException, DataSetException,
FileNotFoundException {
//导出到Excel文件里
/*注意这里导入了poi-3.2-FINAL.jar,在这里我用的dbunit-2.4.9.jar
* 是最新的版本,而poi目前最新的版本是poi-3.10-beta2-20130904.jar,
* 与dbunit的最新版本一起使用会报错 会出现:
* java.lang.NoSuchMethodError: org.apache.poi.hssf.usermodel.HSSFCell.setCellValue(Lorg/apache/poi/hssf/usermodel/HSSFRichTextString;)V
* 而换成poi-3.2-FINAL.jar时则成功导出,生成了两个Sheet,Sheet名为表名
* 即只能导出一个表中的数据,并且只能导出Excel97-2003*.xls版本的文件
* 而使用FlatXmlDataSet能够导出多个表中的数据
*/
if(tableMap != null && !tableMap.isEmpty())
{
for(Entry<String, String> entry : tableMap.entrySet())
{
String tableName = entry.getKey();
String queryStr = entry.getValue();
QueryDataSet dataSet1 = new QueryDataSet(connection);
if(StringUtils.isNotBlank(tableName))
{
if(StringUtils.isNotBlank(queryStr))
{
dataSet1.addTable(tableName, queryStr);
}
else
{
dataSet1.addTable(tableName);
}
writeExcel(dataSet1, new FileOutputStream(FILENAME + tableName +".xls"));
}
}
}
}
/**
* 导出一个EXCEL文件(sheet名为表名)
* @param connection
* @param dataSet
* @param tableMap
* @throws AmbiguousTableNameException
* @throws IOException
* @throws DataSetException
* @throws FileNotFoundException
*/
public static void exportTotalExcelFromDataBase(IDatabaseConnection connection, QueryDataSet dataSet,
Map<String, String> tableMap, String fileName) throws AmbiguousTableNameException, IOException, DataSetException,
FileNotFoundException {
//导出到Excel文件里
/*注意这里导入了poi-3.2-FINAL.jar,在这里我用的dbunit-2.4.9.jar
* 是最新的版本,而poi目前最新的版本是poi-3.10-beta2-20130904.jar,
* 与dbunit的最新版本一起使用会报错 会出现:
* java.lang.NoSuchMethodError: org.apache.poi.hssf.usermodel.HSSFCell.setCellValue(Lorg/apache/poi/hssf/usermodel/HSSFRichTextString;)V
* 而换成poi-3.2-FINAL.jar时则成功导出,生成了两个Sheet,Sheet名为表名
* 即只能导出一个表中的数据,并且只能导出Excel97-2003*.xls版本的文件
* 而使用FlatXmlDataSet能够导出多个表中的数据
*/
if(tableMap != null && !tableMap.isEmpty())
{
for(Entry<String, String> entry : tableMap.entrySet())
{
String tableName = entry.getKey();
String queryStr = entry.getValue();
if(StringUtils.isNotBlank(tableName))
{
if(StringUtils.isNotBlank(queryStr))
{
dataSet.addTable(tableName, queryStr);
}
else
{
dataSet.addTable(tableName);
}
}
}
}
writeExcel(dataSet, new FileOutputStream(FILENAME + fileName));
}
/**
* 导出XML文件,文件名为表名
* @param connection
* @param dataSet
* @param tableMap
* @throws AmbiguousTableNameException
* @throws IOException
* @throws DataSetException
* @throws FileNotFoundException
*/
public static void exportXMLFromDataBase(IDatabaseConnection connection, QueryDataSet dataSet,
Map<String, String> tableMap) throws AmbiguousTableNameException, IOException, DataSetException,
FileNotFoundException {
//导出到Excel文件里
/*注意这里导入了poi-3.2-FINAL.jar,在这里我用的dbunit-2.4.9.jar
* 是最新的版本,而poi目前最新的版本是poi-3.10-beta2-20130904.jar,
* 与dbunit的最新版本一起使用会报错 会出现:
* java.lang.NoSuchMethodError: org.apache.poi.hssf.usermodel.HSSFCell.setCellValue(Lorg/apache/poi/hssf/usermodel/HSSFRichTextString;)V
* 而换成poi-3.2-FINAL.jar时则成功导出,生成了两个Sheet,Sheet名为表名
* 即只能导出一个表中的数据,并且只能导出Excel97-2003*.xls版本的文件
* 而使用FlatXmlDataSet能够导出多个表中的数据
*/
if(tableMap != null && !tableMap.isEmpty())
{
for(Entry<String, String> entry : tableMap.entrySet())
{
String tableName = entry.getKey();
String queryStr = entry.getValue();
QueryDataSet dataSet1 = new QueryDataSet(connection);
if(StringUtils.isNotBlank(tableName))
{
if(StringUtils.isNotBlank(queryStr))
{
dataSet1.addTable(tableName, queryStr);
dataSet.addTable(tableName, queryStr);
}
else
{
dataSet1.addTable(tableName);
dataSet.addTable(tableName);
}
String fileName = FILENAME + tableName + ".xml";
FlatXmlDataSet.write(dataSet1, new FileWriter(fileName), "utf-8");
}
}
}
// writeExcel(dataSet, new FileOutputStream(FILENAME + "dbTest.xls"));
// CsvDataSetWriter w = new CsvDataSetWriter(new File(FILENAME+ ".csv"));
// w.write(dataSet);
// FlatXmlDataSet.write(dataSet, new FileOutputStream(FILENAME));
}
public static Cell writeDateValue(Workbook book, Sheet sheet, int row,
int column, Date value) {
Row poiRow = sheet.getRow(row);
CreationHelper createHelper = book.getCreationHelper();
if (poiRow == null) {
poiRow = sheet.createRow(row);
}
Cell poiCell = poiRow.getCell(column);
if (poiCell == null) {
poiCell = poiRow.createCell(column);
}
CellStyle cellStyle = book.createCellStyle();
cellStyle.setDataFormat(createHelper.createDataFormat().getFormat(
"yyyy-MM-dd HH:mm:ss"));
if (value != null) {
poiCell.setCellValue(value);
} else {
poiCell.setCellValue(new Date());
}
poiCell.setCellStyle(cellStyle);
return poiCell;
}
public static void writeExcel(IDataSet dataSet, OutputStream out) throws IOException, DataSetException
{
HSSFWorkbook workbook = new HSSFWorkbook();
// 定义3种字体
HSSFFont normalFont = PoiUtils.createFont(workbook, "宋体", 200,
(short) (-1), (short) (-1));
HSSFFont boldFont = PoiUtils.createFont(workbook, "宋体", 180,
Font.BOLDWEIGHT_BOLD, (short) (-1));
// 定义基本样式
HSSFCellStyle objCellStyle = PoiUtils.createCellStyle(workbook, normalFont);
// 定义样式——有边框
HSSFCellStyle objBorderCellStyle = PoiUtils.createCellStyle(workbook,objCellStyle, normalFont, CellStyle.ALIGN_CENTER);
objBorderCellStyle.setBorderBottom(CellStyle.BORDER_THIN);// 下边框
objBorderCellStyle.setBorderLeft(CellStyle.BORDER_THIN);// 左边框
objBorderCellStyle.setBorderRight(CellStyle.BORDER_THIN);// 右边框
objBorderCellStyle.setBorderTop(CellStyle.BORDER_THIN);// 上边框
HSSFCellStyle objWhiteCellStyle = PoiUtils.createCellStyle(workbook,
objBorderCellStyle, boldFont, CellStyle.ALIGN_CENTER);
objWhiteCellStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);
objWhiteCellStyle.setFillForegroundColor(HSSFColor.WHITE.index);
// 题头行高度(大)
int iTitileRowHeightB = 35;
//定义样式--日期格式
HSSFCellStyle objWhiteCellStyleRightDate = PoiUtils.createCellStyle(
workbook, objBorderCellStyle, normalFont,HSSFCellStyle.ALIGN_RIGHT);
objWhiteCellStyleRightDate.setDataFormat(workbook.createDataFormat().getFormat("yyyy-MM-dd HH:mm:ss"));
int index = 0;
for(ITableIterator iterator = dataSet.iterator(); iterator.next();)
{
ITable table = iterator.getTable();
ITableMetaData metaData = table.getTableMetaData();
Sheet sheet = workbook.createSheet(metaData.getTableName());
workbook.setSheetName(index, metaData.getTableName());
Row headerRow = sheet.createRow(0);
Column columns[] = metaData.getColumns();
for(int j = 0; j < columns.length; j++)
{
Column column = columns[j];
Cell cell = headerRow.createCell(j);
cell.setCellValue(new HSSFRichTextString(column.getColumnName()));
}
for(int j = 0; j < table.getRowCount(); j++)
{
HSSFRow row = (HSSFRow) PoiUtils.createRow(sheet, j + 1, iTitileRowHeightB);
for(int k = 0; k < columns.length; k++)
{
Column column = columns[k];
Object value = table.getValue(j, column.getColumnName());
if(value == null)
continue;
if (value instanceof Date)
{
PoiUtils.cteateCell(row, k, DateUtil.convertToDate(value, "yyyy-MM-dd HH:mm:ss"), objWhiteCellStyleRightDate);
}
else
{
PoiUtils.cteateCell(row, k, value, objBorderCellStyle);
}
}
}
index++;
}
workbook.write(out);
out.flush();
}
运行后导出excel文件到指定目录。
读取excel文件生成VO
package com.sf.iec.gernaratedata;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import org.apache.commons.lang3.StringUtils;
import com.sf.common.util.DateUtil;
import com.sf.iec.common.util.BigDecimalUtils;
/**
* 从EXCEL数据集文件创建Bean
*/
public class XlsDataSetBeanFactory {
// 从DbUnit的EXCEL数据集文件创建多个bean
public static <T> List<T> createBeans(String file, String tableName, Class<T> clazz)
throws Exception {
InputStream in = XlsDataSetBeanFactory.class.getResourceAsStream(file);
XlsWorkBook workbook = new XlsWorkBook(in);
XlsWorkSheet sheet = workbook.ge