标签:
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONArray;
import net.sf.json.JsonConfig;
import org.apache.commons.collections.MapUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
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;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.ss.util.CellRangeAddress;
import com.gsoft.cos.core.util.Assert;
import com.gsoft.modules.ggcz.utils.GgczUtil;
import com.gsoft.modules.ggcz.utils.TableUtil;
/**
* @ClassName: WorkbookUtil
* @Description: excel工具类
*/
public class WorkbookUtil {
private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
private static DecimalFormat df = new DecimalFormat("0");
@SuppressWarnings("unchecked")
public static HSSFWorkbook export(List<List<ColumnVO>> list, List<?> datas) {
// 声明工作薄
HSSFWorkbook workbook = new HSSFWorkbook();
// 生成表格
HSSFSheet sheet = workbook.createSheet();
// 创建单元格样式
HSSFCellStyle style = workbook.createCellStyle();
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
// style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
// style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
// style.setBorderRight(HSSFCellStyle.BORDER_THIN);
// style.setBorderTop(HSSFCellStyle.BORDER_THIN);
// 表头
HSSFRow row = null;
Map<String, String> keyMap = new HashMap<String, String>();
int totalColumn = 0;
List<String> contains = new ArrayList<String>();
for (int i = 0; i < list.size(); i++) {
List<ColumnVO> columns = list.get(i);
int startColumn = 0;
row = sheet.createRow(i);
int size = 0;
if (i == 0) {
size = columns.size();
} else {
size = totalColumn;
}
int index = 0;
int p = 0;
for (int j = 0; j < size; j++) {
if (i > 0) {
if (p == columns.size()) {
break;
}
}
if (!contains.contains(startColumn + "," + i)) {
ColumnVO column = null;
if (i == 0) {
column = columns.get(j);
} else {
column = columns.get(j - index);
}
if ((Assert.isNotEmpty(column.getHidden()) && column
.getHidden()) || !column.isExported()) {
continue;
}
if (Assert.isNotEmpty(column.getField())) {
if (Assert.isNotEmpty(column.getFieldType())) {
keyMap.put(
String.valueOf(startColumn),
column.getField() + ","
+ column.getFieldType());
} else {
keyMap.put(String.valueOf(startColumn),
column.getField());
}
}
HSSFCell cell = row.createCell(startColumn);
cell.setCellStyle(style);
if (Assert.isNotEmpty(column.getTitle())) {
cell.setCellValue(column.getTitle().replaceAll("<br>",
""));
} else {
cell.setCellValue(column.getTitle());
}
int colspan = 1;
if ((Assert.isNotEmpty(column.getColspan()) && column
.getColspan() > 1)) {
colspan = column.getColspan();
}
int rowspan = 1;
if (Assert.isNotEmpty(column.getRowspan())
&& column.getRowspan() > 1) {
rowspan = column.getRowspan();
}
if (colspan > 1 || rowspan > 1) {
// 合并单元格(startRow,endRow,startColumn,endColumn)
sheet.addMergedRegion(new CellRangeAddress(i, i
+ rowspan - 1, startColumn, startColumn
+ colspan - 1));
}
if (rowspan > 1) {
for (int k = 0; k < rowspan; k++) {
contains.add(startColumn + ","
+ (rowspan - i - 1 + k));
}
}
startColumn += colspan;
p += 1;
} else {
startColumn += 1;
index += 1;
}
}
if (i == 0) {
totalColumn = startColumn;
}
}
//Object object = null;
// 遍历集合
//int rownum = list.size() - 1;
int rownum = list.size();
if (datas != null) {
for (int i = 0; i < datas.size(); i++) {
Map<String, Object> map =(Map<String, Object>) datas.get(i);
int number = 0;
row = sheet.createRow(i + rownum);
/* object = datas.get(i);
row = sheet.createRow(i + rownum + 1);
int number = 0;
Map<String, Object> map = new HashMap<String, Object>();
if (!(object instanceof Map)) {
try {
map = BeanUtils.describe(object);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}*/
for (int j = 0; j < keyMap.size(); j++) {
String key = keyMap.get(String.valueOf(j));
String fieldType = "";
if (key.contains(",")) {
fieldType = key.substring(key.indexOf(",") + 1,
key.length());
key = key.substring(0, key.indexOf(","));
}
String value = MapUtils.getString(map, key);
if (fieldType.equals("date")) {
try {
value = new GgczUtil().getDateToString(value,
"yyyy-MM-dd");
} catch (ParseException e) {
e.printStackTrace();
}
}
HSSFCell cell = row.createCell(number);
cell.setCellValue(value);
number++;
}
}
}
return workbook;
}
/**
* 获取excel中行数据
*/
public static List<Map<String, Object>> getData(InputStream is) {
List<Map<String, Object>> rows = new ArrayList<Map<String, Object>>();
try {
Workbook wb = WorkbookFactory.create(is);
Sheet sheet = wb.getSheetAt(0);
// int lastRowNum = sheet.getLastRowNum();
int rowsCount = sheet.getPhysicalNumberOfRows();
int firstRowNum = sheet.getFirstRowNum();
int cellsCount = 0;
Row row = sheet.getRow(0);
if (row != null) {
cellsCount = row.getPhysicalNumberOfCells();
}
List<String> headers = new ArrayList<String>();
for (int j = 0; j < cellsCount; j++) {
Cell cell = row.getCell(j);
headers.add(getCellValue(cell));
}
Map<String, Object> map = null;
for (int i = firstRowNum + 1; i < rowsCount; i++) {
row = sheet.getRow(i);
if (row == null) {
continue;
}
map = new HashMap<String, Object>();
String value = null;
for (int j = 0; j < cellsCount; j++) {
Cell cell = row.getCell(j);
value = getCellValue(cell);
map.put(headers.get(j), value);
}
rows.add(map);
}
} catch (InvalidFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return rows;
}
/**
* 获取excel中行数据
*/
public static List<Map<String, Object>> getDataToField(InputStream is) {
List<Map<String, Object>> rows = new ArrayList<Map<String, Object>>();
try {
Workbook wb = WorkbookFactory.create(is);
Sheet sheet = wb.getSheetAt(0);
// int lastRowNum = sheet.getLastRowNum();
int rowsCount = sheet.getPhysicalNumberOfRows();
int firstRowNum = sheet.getFirstRowNum();
int cellsCount = 0;
Row row = sheet.getRow(0);
if (row != null) {
cellsCount = row.getPhysicalNumberOfCells();
}
List<String> headers = new ArrayList<String>();
for (int j = 0; j < cellsCount; j++) {
Cell cell = row.getCell(j);
headers.add(getCellValue(cell));
}
Map<String, Object> map = null;
for (int i = firstRowNum + 2; i < rowsCount; i++) {
row = sheet.getRow(i);
if (row == null) {
continue;
}
map = new HashMap<String, Object>();
String value = null;
for (int j = 0; j < cellsCount; j++) {
Cell cell = row.getCell(j);
value = getCellValue(cell);
map.put(headers.get(j), value);
}
rows.add(map);
}
} catch (InvalidFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return rows;
}
/**
* 获取单元格数据
*/
protected static String getCellValue(Cell cell) {
String cellValue = "";
if (cell != null) {
switch (cell.getCellType()) {
case Cell.CELL_TYPE_STRING:
cellValue = cell.getStringCellValue();
break;
case Cell.CELL_TYPE_NUMERIC:
String dataFormat = cell.getCellStyle().getDataFormatString();
if (DateUtil.isCellDateFormatted(cell)) {
cellValue = sdf.format(cell.getDateCellValue());
} else if ("@".equals(dataFormat)) {
cellValue = df.format(cell.getNumericCellValue());
} else {
cellValue = String.valueOf(cell.getNumericCellValue());
DecimalFormat df = new DecimalFormat("#.#########");
cellValue = df.format(Double.valueOf(cellValue));
}
break;
case Cell.CELL_TYPE_BOOLEAN:
cellValue = String.valueOf(cell.getBooleanCellValue());
break;
case Cell.CELL_TYPE_FORMULA:
cellValue = cell.getCellFormula();
break;
default:
cellValue = "";
}
}
return cellValue;
}
/**
*
* @param request
* @param response
* @param operate
* 导入还是导出 export or print
* @param title
* 表明
* @param columnJson
* 列值
* @param datas
* 数据集
* @throws UnsupportedEncodingException
* @throws IOException
*/
public void export(HttpServletRequest request,
HttpServletResponse response, String operate, String title,
String columnJson, List<?> datas)
throws UnsupportedEncodingException, IOException {
List<List<ColumnVO>> list = new ArrayList<List<ColumnVO>>();
JsonConfig jsonConfig = new JsonConfig();
jsonConfig.setIgnoreDefaultExcludes(true);
jsonConfig.setExcludes(new String[] { "checkbox", "boxWidth",
"deltaWidth", "cellClass", "iconCls", "sortable", "order",
"editor", "auto" });
JSONArray array = JSONArray.fromObject(columnJson, jsonConfig);
for (int i = 0; i < array.size(); i++) {
JSONArray columns = (JSONArray) array.get(i);
@SuppressWarnings("unchecked")
List<ColumnVO> temp = (List<ColumnVO>) JSONArray.toList(columns,
new ColumnVO(), jsonConfig);
list.add(temp);
}
if ("export".equals(operate)) {
try {
HSSFWorkbook workbook = WorkbookUtil.export(list, datas);
response.setContentType("APPLICATION/x-msdownload");
// response.setHeader(
// "Content-Disposition",
// "attachment;filename*=UTF-8‘‘"
// + URLEncoder.encode("测试导出.xls", "UTF-8"));
response.addHeader(
"Content-Disposition",
"attachment;filename="
+ new String(title.getBytes("GBK"), "ISO8859-1")
+ ".xls");
/*response.setHeader("Content-disposition", "attachment;filename="
+ URLEncoder.encode(title+".xls", "UTF-8"));*/
OutputStream os = response.getOutputStream();
workbook.write(os);
os.close();
} catch (NumberFormatException e) {
e.printStackTrace();
}
} else if ("print".equals(operate)) {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=UTF-8");
response.setCharacterEncoding("UTF-8");
OutputStream os = response.getOutputStream();
String text = TableUtil.print(list, title, datas);
os.write(text.getBytes("UTF-8"));
}
}
/**
*
* @param request
* @param response
* @param operate
* 导入还是导出 export or print
* @param title
* 表明
* @param columnJson
* 列值
* @param datas
* 数据集
* @throws UnsupportedEncodingException
* @throws IOException
*/
public void exportTree(HttpServletRequest request,
HttpServletResponse response, String operate, String title,
String columnJson, List<?> datas)
throws UnsupportedEncodingException, IOException {
List<List<ColumnVO>> list = new ArrayList<List<ColumnVO>>();
JsonConfig jsonConfig = new JsonConfig();
jsonConfig.setIgnoreDefaultExcludes(true);
jsonConfig.setExcludes(new String[] { "checkbox", "boxWidth",
"deltaWidth", "cellClass", "iconCls", "sortable", "order",
"editor", "auto" });
JSONArray array = JSONArray.fromObject(columnJson, jsonConfig);
for (int i = 0; i < array.size(); i++) {
JSONArray columns = (JSONArray) array.get(i);
@SuppressWarnings("unchecked")
List<ColumnVO> temp = (List<ColumnVO>) JSONArray.toList(columns,
new ColumnVO(), jsonConfig);
list.add(temp);
}
if ("export".equals(operate)) {
try {
HSSFWorkbook workbook = WorkbookUtil.exportTree(list, datas);
response.setContentType("APPLICATION/x-msdownload");
// response.setHeader(
// "Content-Disposition",
// "attachment;filename*=UTF-8‘‘"
// + URLEncoder.encode("测试导出.xls", "UTF-8"));
response.addHeader(
"Content-Disposition",
"attachment;filename="
+ new String(title.getBytes("GBK"), "ISO8859-1")
+ ".xls");
/*response.setHeader("Content-disposition", "attachment;filename="
+ URLEncoder.encode(title+".xls", "UTF-8"));*/
OutputStream os = response.getOutputStream();
workbook.write(os);
os.close();
} catch (NumberFormatException e) {
e.printStackTrace();
}
} else if ("print".equals(operate)) {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=UTF-8");
response.setCharacterEncoding("UTF-8");
OutputStream os = response.getOutputStream();
String text = TableUtil.print(list, title, datas);
os.write(text.getBytes("UTF-8"));
}
}
@SuppressWarnings("unchecked")
public static HSSFWorkbook exportTree(List<List<ColumnVO>> list, List<?> datas) {
// 声明工作薄
HSSFWorkbook workbook = new HSSFWorkbook();
// 生成表格
HSSFSheet sheet = workbook.createSheet();
// 创建单元格样式
HSSFCellStyle style = workbook.createCellStyle();
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
// style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
// style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
// style.setBorderRight(HSSFCellStyle.BORDER_THIN);
// style.setBorderTop(HSSFCellStyle.BORDER_THIN);
// 表头
HSSFRow row = null;
Map<String, String> keyMap = new HashMap<String, String>();
int totalColumn = 0;
List<String> contains = new ArrayList<String>();
for (int i = 0; i < list.size(); i++) {
List<ColumnVO> columns = list.get(i);
int startColumn = 0;
row = sheet.createRow(i);
int size = 0;
if (i == 0) {
size = columns.size();
} else {
size = totalColumn;
}
int index = 0;
int p = 0;
for (int j = 0; j < size; j++) {
if (i > 0) {
if (p == columns.size()) {
break;
}
}
if (!contains.contains(startColumn + "," + i)) {
ColumnVO column = null;
if (i == 0) {
column = columns.get(j);
} else {
column = columns.get(j - index);
}
if ((Assert.isNotEmpty(column.getHidden()) && column
.getHidden()) || !column.isExported()) {
continue;
}
if (Assert.isNotEmpty(column.getField())) {
if (Assert.isNotEmpty(column.getFieldType())) {
keyMap.put(
String.valueOf(startColumn),
column.getField() + ","
+ column.getFieldType());
} else {
keyMap.put(String.valueOf(startColumn),
column.getField());
}
}
HSSFCell cell = row.createCell(startColumn);
cell.setCellStyle(style);
if (Assert.isNotEmpty(column.getTitle())) {
cell.setCellValue(column.getTitle().replaceAll("<br>",
""));
} else {
cell.setCellValue(column.getTitle());
}
int colspan = 1;
if ((Assert.isNotEmpty(column.getColspan()) && column
.getColspan() > 1)) {
colspan = column.getColspan();
}
int rowspan = 1;
if (Assert.isNotEmpty(column.getRowspan())
&& column.getRowspan() > 1) {
rowspan = column.getRowspan();
}
if (colspan > 1 || rowspan > 1) {
// 合并单元格(startRow,endRow,startColumn,endColumn)
sheet.addMergedRegion(new CellRangeAddress(i, i
+ rowspan - 1, startColumn, startColumn
+ colspan - 1));
}
if (rowspan > 1) {
for (int k = 0; k < rowspan; k++) {
contains.add(startColumn + ","
+ (rowspan - i - 1 + k));
}
}
startColumn += colspan;
p += 1;
} else {
startColumn += 1;
index += 1;
}
}
if (i == 0) {
totalColumn = startColumn;
}
}
//Object object = null;
// 遍历集合
//int rownum = list.size() - 1;
int rownum = list.size();
int valueRownum=0;
if (datas != null) {
for (int i = 0; i < datas.size(); i++) {
Map<String, Object> map =(Map<String, Object>) datas.get(i);
int number = 0;
row = sheet.createRow(i + rownum+valueRownum);
for (int j = 0; j < keyMap.size()+1; j++) {
if(j==keyMap.size()){
valueRownum+=loadChildren( rownum, valueRownum, row, sheet, i, map, keyMap);
}else{
String key = keyMap.get(String.valueOf(j));
String fieldType = "";
if (key.contains(",")) {
fieldType = key.substring(key.indexOf(",") + 1,
key.length());
key = key.substring(0, key.indexOf(","));
}
String value = MapUtils.getString(map, key);
if (fieldType.equals("date")) {
try {
value = new GgczUtil().getDateToString(value,
"yyyy-MM-dd");
} catch (ParseException e) {
e.printStackTrace();
}
}
HSSFCell cell = row.createCell(number);
cell.setCellValue(value);
}
number++;
}
}
}
return workbook;
}
/**
* 加载children
* @param rownum
* @param valueRownum
* @param row
* @param sheet
* @param i
* @param map
* @param keyMap
*/
@SuppressWarnings("unchecked")
public static int loadChildren(int rownum,int valueRownum,HSSFRow row,HSSFSheet sheet,int i,Map<String, Object> map,Map<String, String> keyMap){
List<Map<String, Object>> valueList= new ArrayList<Map<String,Object>>();
Object object=map.get("children");
if(Assert.isNotEmpty(object)){
valueList=(List<Map<String, Object>>) object;
for (int k = 0; k < valueList.size(); k++) {
Map<String, Object> valueMap =(Map<String, Object>) valueList.get(i);
int valueNumber = 0;
row = sheet.createRow(i + k + rownum+valueRownum+1);
for (int m = 0; m < keyMap.size(); m++) {
if(m==keyMap.size()){
loadChildren( rownum, valueRownum, row, sheet, i, map, keyMap);
}else{
String valueKey = keyMap.get(String.valueOf(m));
String valueFieldType = "";
if (valueKey.contains(",")) {
valueFieldType = valueKey.substring(valueKey.indexOf(",") + 1,
valueKey.length());
valueKey = valueKey.substring(0, valueKey.indexOf(","));
}
String value = MapUtils.getString(valueMap, valueKey);
if (valueFieldType.equals("date")) {
try {
value = new GgczUtil().getDateToString(value,
"yyyy-MM-dd");
} catch (ParseException e) {
e.printStackTrace();
}
}
HSSFCell cell = row.createCell(valueNumber);
cell.setCellValue(value);
valueNumber++;
}
}
}
valueRownum=valueList.size();
}
return valueRownum;
}
/**
* 汇总明细table和 datagrid 拼接
*
* @param request
* @param response
* @param operate
* 导入还是导出 export or print
* @param title
* 表明
* @param columnJson
* 列值
* @param datas
* 数据集
* @throws UnsupportedEncodingException
* @throws IOException
*/
@SuppressWarnings("unchecked")
public void exportToCollect(HttpServletRequest request,
HttpServletResponse response, String operate, String title,
String columnJson, List<?> datas)
throws UnsupportedEncodingException, IOException {
columnJson = columnJson.replaceAll("undefined", "");
List<List<List<ColumnVO>>> list = new ArrayList<List<List<ColumnVO>>>();
JsonConfig jsonConfig = new JsonConfig();
jsonConfig.setIgnoreDefaultExcludes(true);
jsonConfig.setExcludes(new String[] { "checkbox", "boxWidth",
"deltaWidth", "cellClass", "iconCls", "sortable", "order",
"editor", "auto" });
JSONArray array = JSONArray.fromObject(columnJson, jsonConfig);
for (int i = 0; i < array.size(); i++) {
List<List<ColumnVO>> list1 = (List<List<ColumnVO>>) array.get(i);
List<List<ColumnVO>> list2 = new ArrayList<List<ColumnVO>>();
for (int j = 0; j < list1.size(); j++) {
JSONArray columns = (JSONArray) list1.get(j);
List<ColumnVO> temp = (List<ColumnVO>) JSONArray.toList(
columns, new ColumnVO(), jsonConfig);
list2.add(temp);
}
list.add(list2);
}
if ("export".equals(operate)) {
try {
HSSFWorkbook workbook = WorkbookUtil.exportToCollect(list,
datas);
response.setContentType("APPLICATION/x-msdownload");
response.addHeader(
"Content-Disposition",
"attachment;filename="
+ new String(title.getBytes("GBK"), "ISO8859-1")
+ ".xls");
/*response.setHeader("Content-disposition", "attachment;filename="
+ URLEncoder.encode(title+".xls", "UTF-8"));*/
OutputStream os = response.getOutputStream();
workbook.write(os);
os.close();
} catch (NumberFormatException e) {
e.printStackTrace();
}
}
}
@SuppressWarnings("unchecked")
public static HSSFWorkbook exportToCollect(List<List<List<ColumnVO>>> list,
List<?> datas) {
// 声明工作薄
HSSFWorkbook workbook = new HSSFWorkbook();
// 生成表格
HSSFSheet sheet = workbook.createSheet();
// 创建单元格样式
HSSFCellStyle style = workbook.createCellStyle();
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
// 表头
HSSFRow row = null;
int rownum = 0;
Map<String, String> keyMap = new HashMap<String, String>();
for (int f = 0; f < list.size(); f++) {
List<List<ColumnVO>> list1 = list.get(f);
int totalColumn = 0;
List<String> contains = new ArrayList<String>();
for (int i = 0; i < list1.size(); i++) {
List<ColumnVO> columns = list1.get(i);
int startColumn = 0;
row = sheet.createRow(i + rownum);
int size = 0;
if (i == 0) {
size = columns.size();
} else {
size = totalColumn;
}
int index = 0;
int p = 0;
for (int j = 0; j < size; j++) {
if (i > 0) {
if (p == columns.size()) {
break;
}
}
if (!contains.contains(startColumn + "," + (i + rownum))) {
ColumnVO column = null;
if (i == 0) {
column = columns.get(j);
} else {
column = columns.get(j - index);
}
if ((Assert.isNotEmpty(column.getHidden()) && column
.getHidden()) || !column.isExported()) {
continue;
}
if (Assert.isNotEmpty(column.getField())) {
keyMap.put(String.valueOf(startColumn),
column.getField());
}
HSSFCell cell = row.createCell(startColumn);
cell.setCellStyle(style);
if (Assert.isNotEmpty(column.getTitle())) {
cell.setCellValue(column.getTitle().replaceAll(
"<br>", ""));
} else {
cell.setCellValue(column.getTitle());
}
int colspan = 1;
if ((Assert.isNotEmpty(column.getColspan()) && column
.getColspan() > 1)) {
colspan = column.getColspan();
}
int rowspan = 1;
if (Assert.isNotEmpty(column.getRowspan())
&& column.getRowspan() > 1) {
rowspan = column.getRowspan();
}
if (colspan > 1 || rowspan > 1) {
// 合并单元格(startRow,endRow,startColumn,endColumn)
sheet.addMergedRegion(new CellRangeAddress(i
+ rownum, i + rownum + rowspan - 1,
startColumn, startColumn + colspan - 1));
}
if (rowspan > 1) {
for (int k = 0; k < rowspan; k++) {
contains.add(startColumn + ","
+ (rowspan - i + rownum - 1 + k));
}
}
startColumn += colspan;
p += 1;
} else {
startColumn += 1;
index += 1;
}
}
if (i == 0) {
totalColumn = startColumn;
}
}
if (list.size() > 1 && f == list.size() - 2) {
rownum += list.get(f).size() + 1;
} else {
rownum += list.get(f).size();
}
}
//Object object = null;
// 遍历集合
//int rownum = list.size() - 1;
//rownum = list.get(1).size();
if (datas != null) {
for (int i = 0; i < datas.size(); i++) {
Map<String, Object> map = (Map<String, Object>) datas.get(i);
int number = 0;
row = sheet.createRow(i + rownum);
for (int j = 0; j < keyMap.size(); j++) {
String key = keyMap.get(String.valueOf(j));
String value = MapUtils.getString(map, key);
HSSFCell cell = row.createCell(number);
cell.setCellValue(value);
number++;
}
}
}
return workbook;
}
/**
* 根据List Map<String,Object>导出Excel
*
* @param request
* @param response
* @param operate
* @param title
* 表名
* @param TitleMp
* 表头map,为空则根据datas中Map的Key
* @param datas
* 数据集
* @throws UnsupportedEncodingException
* @throws IOException
*/
public void exportToTitleMap(HttpServletRequest request,
HttpServletResponse response, String title,
Map<String, String> TitleMp, List<?> datas)
throws UnsupportedEncodingException, IOException {
try {
HSSFWorkbook workbook = WorkbookUtil.exportToTitleMap(TitleMp,
datas);
response.setContentType("APPLICATION/x-msdownload");
response.addHeader("Content-Disposition", "attachment;filename="
+ new String(title.getBytes("GBK"), "ISO8859-1") + ".xls");
OutputStream os = response.getOutputStream();
workbook.write(os);
os.close();
} catch (NumberFormatException e) {
e.printStackTrace();
}
}
@SuppressWarnings({ "unchecked", "rawtypes" })
public static HSSFWorkbook exportToTitleMap(Map<String, String> titleMp,
List<?> datas) {
// 声明工作薄
HSSFWorkbook workbook = new HSSFWorkbook();
// 生成表格
HSSFSheet sheet = workbook.createSheet();
// 创建单元格样式
HSSFCellStyle style = workbook.createCellStyle();
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);
style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);
// 表头
HSSFRow row = null;
List<String> keyArray = new ArrayList<String>();
row = sheet.createRow(0);
Set mapKey = null;
if (Assert.isNotEmpty(titleMp)) {
mapKey = titleMp.keySet();
} else {
if (Assert.isNotEmpty(datas)) {
Map<String, Object> map = (Map<String, Object>) datas.get(0);
mapKey = map.keySet();
} else {
return workbook;
}
}
int s = 0;
for (Object object : mapKey) {
HSSFCell cell = row.createCell(s);
cell.setCellStyle(style);
keyArray.add(object.toString());
if (Assert.isNotEmpty(titleMp)) {
cell.setCellValue(titleMp.get(object));
} else {
cell.setCellValue(object.toString());
}
s++;
}
if (datas != null) {
for (int i = 0; i < datas.size(); i++) {
Map<String, Object> map = (Map<String, Object>) datas.get(i);
row = sheet.createRow(i + 1);
for (int j = 0; j < keyArray.size(); j++) {
String key = keyArray.get(j);
String value = MapUtils.getString(map, key);
HSSFCell cell = row.createCell(j);
cell.setCellValue(value);
}
}
}
return workbook;
}
}
easyui DataGrid 工具类之 WorkbookUtil class
标签:
原文地址:http://www.cnblogs.com/ckaifeng/p/5130941.html