getfieldnames android不要标题把第一行作为标题行

java:POI导出excel
编辑:www.fx114.net
本篇文章主要介绍了"java:POI导出excel ",主要涉及到java:POI导出excel 方面的内容,对于java:POI导出excel 感兴趣的同学可以参考一下。
是一个开源项目,专用于java平台上操作MS OFFICE,企业应用开发中可用它方便导出Excel.
下面是使用示例:
1、maven中先添加依赖项
&dependency&
2
&groupId&org.apache.poi&/groupId&
3
&artifactId&poi&/artifactId&
4
&version&3.11&/version&
5
&/dependency&
2、最基本的导出示例
a) 先定义一个基本的类AwbData
1 package blogs.yjmyzz.test.
3 public class AwbDto {
public AwbDto() {
public AwbDto(String awbNumber, String agent) {
11
super();
12
this.awbNumber = awbN
13
this.agent =
14
* 运单号
18
private String awbN
20
* 代理人
23
private S
25
public String getAwbNumber() {
27
return awbN
28
public void setAwbNumber(String awbNumber) {
31
this.awbNumber = awbN
32
public String getAgent() {
35
public void setAgent(String agent) {
39
this.agent =
40
View Code
b) 伪造点数据
private List&AwbDto& getData1() {
List&AwbDto& data = new ArrayList&AwbDto&();
for (int i = 0; i & 1000; i++) {
data.add(new AwbDto("112-" + FileUtil.leftPad(i + "", 8, '0'), "张三"));
private List&AwbDto& getData2() {
10
List&AwbDto& data = new ArrayList&AwbDto&();
11
for (int i = 0; i & 1000; i++) {
12
data.add(new AwbDto("999-" + FileUtil.leftPad(i + "", 8, '0'), "李四"));
13
View Code
上面都是准备工作,下面才是重点:
public void testExcelExport() throws Exception {
// 创建excel
HSSFWorkbook wb = new HSSFWorkbook();
// 创建sheet
HSSFSheet sheet = wb.createSheet("运单数据");
// 创建一行
11
HSSFRow rowTitle = sheet.createRow(0);
12
// 创建标题栏样式
14
HSSFCellStyle styleTitle = wb.createCellStyle();
15
styleTitle.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 居中
16
HSSFFont fontTitle = wb.createFont();
17
// 宋体加粗
18
fontTitle.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
19
fontTitle.setFontName("宋体");
20
fontTitle.setFontHeight((short) 200);
21
styleTitle.setFont(fontTitle);
22
// 在行上创建1列
24
HSSFCell cellTitle = rowTitle.createCell(0);
25
// 列标题及样式
27
cellTitle.setCellValue("运单号");
28
cellTitle.setCellStyle(styleTitle);
29
// 在行上创建2列
31
cellTitle = rowTitle.createCell(1);
32
cellTitle.setCellValue("代理人");
33
cellTitle.setCellStyle(styleTitle);
34
HSSFCellStyle styleCenter = wb.createCellStyle();
36
styleCenter.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 居中
37
// 取数据
39
List&AwbDto& data = getData1();
40
for (int i = 0; i & data.size(); i++) {
42
AwbDto item = data.get(i);
44
HSSFRow row = sheet.createRow(i + 1);
45
HSSFCell cell = row.createCell(0);
47
cell.setCellValue(item.getAwbNumber());
48
cell.setCellStyle(styleCenter);
49
cell = row.createCell(1);
51
cell.setCellValue(item.getAgent());
52
cell.setCellStyle(styleCenter);
53
FileOutputStream fout = new FileOutputStream("r:/awb.xls");
56
wb.write(fout);
57
fout.close();
58
wb.close();
59
System.out.println("导出完成!");
61
View Code
导出后,大致是这个样子:
3、通用的Excel导出类
对于格式不太复杂的常规excel,如果每次都要写上面这一堆代码,当然有点2,已经有,借来用一下(再次向作者表示感谢),不过这份代码年头略久,有些方法已经被现在的版本标识为过时,略微改进了一下下,贴在这里:
1 package blogs.yjmyzz.
3 import java.io.ByteArrayOutputS
4 import java.io.IOE
5 import java.text.SimpleDateF
6 import java.util.D
7 import java.util.LinkedHashM
8 import java.util.L
9 import java.util.S
10 import java.util.Map.E
11 import org.apache.poi.hssf.usermodel.HSSFC
12 import org.apache.poi.hssf.usermodel.HSSFR
13 import org.apache.poi.hssf.usermodel.HSSFS
14 import org.apache.poi.hssf.usermodel.HSSFW
15 import org.apache.poi.ss.usermodel.CellS
16 import org.apache.poi.ss.usermodel.F
17 import org.apache.poi.ss.usermodel.IndexedC
18 import org.apache.poi.ss.util.CellRangeA
20 public class ExcelUtil {
private static HSSFW
private static CellStyle titleS // 标题行样式
private static Font titleF // 标题行字体
private static CellStyle dateS // 日期行样式
private static Font dateF // 日期行字体
private static CellStyle headS // 表头行样式
private static Font headF // 表头行字体
private static CellStyle contentS // 内容行样式
private static Font contentF // 内容行字体
* 导出文件
* @param setInfo
* @param outputExcelFileName
* @throws IOException
public static boolean export2File(ExcelExportData setInfo,
String outputExcelFileName) throws Exception {
return FileUtil.write(outputExcelFileName, export2ByteArray(setInfo),
true, true);
* 导出到byte数组
* @param setInfo
* @throws Exception
public static byte[] export2ByteArray(ExcelExportData setInfo)
throws Exception {
return export2Stream(setInfo).toByteArray();
* 导出到流
* @param setInfo
* @throws Exception
public static ByteArrayOutputStream export2Stream(ExcelExportData setInfo)
throws Exception {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
Set&Entry&String, List&?&&& set = setInfo.getDataMap().entrySet();
String[] sheetNames = new String[setInfo.getDataMap().size()];
int sheetNameNum = 0;
for (Entry&String, List&?&& entry : set) {
sheetNames[sheetNameNum] = entry.getKey();
sheetNameNum++;
HSSFSheet[] sheets = getSheets(setInfo.getDataMap().size(), sheetNames);
int sheetNum = 0;
for (Entry&String, List&?&& entry : set) {
List&?& objs = entry.getValue();
createTableTitleRow(setInfo, sheets, sheetNum);
createTableDateRow(setInfo, sheets, sheetNum);
creatTableHeadRow(setInfo, sheets, sheetNum);
String[] fieldNames = setInfo.getFieldNames().get(sheetNum);
int rowNum = 3;
for (Object obj : objs) {
HSSFRow contentRow = sheets[sheetNum].createRow(rowNum);
contentRow.setHeight((short) 300);
100
HSSFCell[] cells = getCells(contentRow, setInfo.getFieldNames()
101
.get(sheetNum).length);
102
int cellNum = 1; // 去掉一列序号,因此从1开始
103
if (fieldNames != null) {
104
for (int num = 0; num & fieldNames. num++) {
105
Object value = ReflectionUtil.invokeGetterMethod(obj,
107
fieldNames[num]);
108
cells[cellNum].setCellValue(value == null ? "" : value
109
.toString());
110
cellNum++;
111
rowNum++;
114
adjustColumnSize(sheets, sheetNum, fieldNames); // 自动调整列宽
116
sheetNum++;
117
wb.write(outputStream);
119
return outputS
120
* @Description: 初始化
124
private static void init() {
126
wb = new HSSFWorkbook();
127
titleFont = wb.createFont();
129
titleStyle = wb.createCellStyle();
130
dateStyle = wb.createCellStyle();
131
dateFont = wb.createFont();
132
headStyle = wb.createCellStyle();
133
headFont = wb.createFont();
134
contentStyle = wb.createCellStyle();
135
contentFont = wb.createFont();
136
initTitleCellStyle();
138
initTitleFont();
139
initDateCellStyle();
140
initDateFont();
141
initHeadCellStyle();
142
initHeadFont();
143
initContentCellStyle();
144
initContentFont();
145
* @Description: 自动调整列宽
149
private static void adjustColumnSize(HSSFSheet[] sheets, int sheetNum,
151
String[] fieldNames) {
152
for (int i = 0; i & fieldNames.length + 1; i++) {
153
sheets[sheetNum].autoSizeColumn(i, true);
154
* @Description: 创建标题行(需合并单元格)
159
private static void createTableTitleRow(ExcelExportData setInfo,
161
HSSFSheet[] sheets, int sheetNum) {
162
CellRangeAddress titleRange = new CellRangeAddress(0, 0, 0, setInfo
163
.getFieldNames().get(sheetNum).length);
164
sheets[sheetNum].addMergedRegion(titleRange);
165
HSSFRow titleRow = sheets[sheetNum].createRow(0);
166
titleRow.setHeight((short) 800);
167
HSSFCell titleCell = titleRow.createCell(0);
168
titleCell.setCellStyle(titleStyle);
169
titleCell.setCellValue(setInfo.getTitles()[sheetNum]);
170
* @Description: 创建日期行(需合并单元格)
174
private static void createTableDateRow(ExcelExportData setInfo,
176
HSSFSheet[] sheets, int sheetNum) {
177
CellRangeAddress dateRange = new CellRangeAddress(1, 1, 0, setInfo
178
.getFieldNames().get(sheetNum).length);
179
sheets[sheetNum].addMergedRegion(dateRange);
180
HSSFRow dateRow = sheets[sheetNum].createRow(1);
181
dateRow.setHeight((short) 350);
182
HSSFCell dateCell = dateRow.createCell(0);
183
dateCell.setCellStyle(dateStyle);
184
// dateCell.setCellValue("导出时间:" + new
185
// SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
186
// .format(new Date()));
187
dateCell.setCellValue(new SimpleDateFormat("yyyy-MM-dd")
188
.format(new Date()));
189
* @Description: 创建表头行(需合并单元格)
193
private static void creatTableHeadRow(ExcelExportData setInfo,
195
HSSFSheet[] sheets, int sheetNum) {
196
// 表头
197
HSSFRow headRow = sheets[sheetNum].createRow(2);
198
headRow.setHeight((short) 350);
199
// 序号列
200
HSSFCell snCell = headRow.createCell(0);
201
snCell.setCellStyle(headStyle);
202
snCell.setCellValue("序号");
203
// 列头名称
204
for (int num = 1, len = setInfo.getColumnNames().get(sheetNum). num &= num++) {
205
HSSFCell headCell = headRow.createCell(num);
206
headCell.setCellStyle(headStyle);
207
headCell.setCellValue(setInfo.getColumnNames().get(sheetNum)[num - 1]);
208
* @Description: 创建所有的Sheet
213
private static HSSFSheet[] getSheets(int num, String[] names) {
215
HSSFSheet[] sheets = new HSSFSheet[num];
216
for (int i = 0; i & i++) {
217
sheets[i] = wb.createSheet(names[i]);
218
return
220
* @Description: 创建内容行的每一列(附加一列序号)
224
private static HSSFCell[] getCells(HSSFRow contentRow, int num) {
226
HSSFCell[] cells = new HSSFCell[num + 1];
227
for (int i = 0, len = cells. i & i++) {
229
cells[i] = contentRow.createCell(i);
230
cells[i].setCellStyle(contentStyle);
231
// 设置序号列值,因为出去标题行和日期行,所有-2
234
cells[0].setCellValue(contentRow.getRowNum() - 2);
235
return
237
* @Description: 初始化标题行样式
241
private static void initTitleCellStyle() {
243
titleStyle.setAlignment(CellStyle.ALIGN_CENTER);
244
titleStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
245
titleStyle.setFont(titleFont);
246
titleStyle.setFillBackgroundColor(IndexedColors.SKY_BLUE.index);
247
* @Description: 初始化日期行样式
251
private static void initDateCellStyle() {
253
dateStyle.setAlignment(CellStyle.ALIGN_CENTER_SELECTION);
254
dateStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
255
dateStyle.setFont(dateFont);
256
dateStyle.setFillBackgroundColor(IndexedColors.SKY_BLUE.index);
257
* @Description: 初始化表头行样式
261
private static void initHeadCellStyle() {
263
headStyle.setAlignment(CellStyle.ALIGN_CENTER);
264
headStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
265
headStyle.setFont(headFont);
266
headStyle.setFillBackgroundColor(IndexedColors.YELLOW.index);
267
headStyle.setBorderTop(CellStyle.BORDER_MEDIUM);
268
headStyle.setBorderBottom(CellStyle.BORDER_THIN);
269
headStyle.setBorderLeft(CellStyle.BORDER_THIN);
270
headStyle.setBorderRight(CellStyle.BORDER_THIN);
271
headStyle.setTopBorderColor(IndexedColors.BLUE.index);
272
headStyle.setBottomBorderColor(IndexedColors.BLUE.index);
273
headStyle.setLeftBorderColor(IndexedColors.BLUE.index);
274
headStyle.setRightBorderColor(IndexedColors.BLUE.index);
275
* @Description: 初始化内容行样式
279
private static void initContentCellStyle() {
281
contentStyle.setAlignment(CellStyle.ALIGN_CENTER);
282
contentStyle.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
283
contentStyle.setFont(contentFont);
284
contentStyle.setBorderTop(CellStyle.BORDER_THIN);
285
contentStyle.setBorderBottom(CellStyle.BORDER_THIN);
286
contentStyle.setBorderLeft(CellStyle.BORDER_THIN);
287
contentStyle.setBorderRight(CellStyle.BORDER_THIN);
288
contentStyle.setTopBorderColor(IndexedColors.BLUE.index);
289
contentStyle.setBottomBorderColor(IndexedColors.BLUE.index);
290
contentStyle.setLeftBorderColor(IndexedColors.BLUE.index);
291
contentStyle.setRightBorderColor(IndexedColors.BLUE.index);
292
contentStyle.setWrapText(true); // 字段换行
293
* @Description: 初始化标题行字体
297
private static void initTitleFont() {
299
titleFont.setFontName("华文楷体");
300
titleFont.setFontHeightInPoints((short) 20);
301
titleFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
302
titleFont.setCharSet(Font.DEFAULT_CHARSET);
303
titleFont.setColor(IndexedColors.BLUE_GREY.index);
304
* @Description: 初始化日期行字体
308
private static void initDateFont() {
310
dateFont.setFontName("隶书");
311
dateFont.setFontHeightInPoints((short) 10);
312
dateFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
313
dateFont.setCharSet(Font.DEFAULT_CHARSET);
314
dateFont.setColor(IndexedColors.BLUE_GREY.index);
315
* @Description: 初始化表头行字体
319
private static void initHeadFont() {
321
headFont.setFontName("宋体");
322
headFont.setFontHeightInPoints((short) 10);
323
headFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
324
headFont.setCharSet(Font.DEFAULT_CHARSET);
325
headFont.setColor(IndexedColors.BLUE_GREY.index);
326
* @Description: 初始化内容行字体
330
private static void initContentFont() {
332
contentFont.setFontName("宋体");
333
contentFont.setFontHeightInPoints((short) 10);
334
contentFont.setBoldweight(Font.BOLDWEIGHT_NORMAL);
335
contentFont.setCharSet(Font.DEFAULT_CHARSET);
336
contentFont.setColor(IndexedColors.BLUE_GREY.index);
337
* Excel导出数据类
341
* @author jimmy
343
public static class ExcelExportData {
346
* 导出数据 key:String 表示每个Sheet的名称 value:List&?& 表示每个Sheet里的所有数据行
349
private LinkedHashMap&String, List&?&& dataM
351
* 每个Sheet里的顶部大标题
354
private String[]
356
* 单个sheet里的数据列标题
359
private List&String[]& columnN
361
* 单个sheet里每行数据的列对应的对象属性名称
364
private List&String[]& fieldN
366
public List&String[]& getFieldNames() {
368
return fieldN
369
public void setFieldNames(List&String[]& fieldNames) {
372
this.fieldNames = fieldN
373
public String[] getTitles() {
376
return
377
public void setTitles(String[] titles) {
380
this.titles =
381
public List&String[]& getColumnNames() {
384
return columnN
385
public void setColumnNames(List&String[]& columnNames) {
388
this.columnNames = columnN
389
public LinkedHashMap&String, List&?&& getDataMap() {
392
return dataM
393
public void setDataMap(LinkedHashMap&String, List&?&& dataMap) {
396
this.dataMap = dataM
397
View Code
里面提供了3个方法,可用于导出到文件、byte数组、以及流,其中有一个反射工具类:
1 package blogs.yjmyzz.
3 import java.lang.reflect.F
4 import java.lang.reflect.InvocationTargetE
5 import java.lang.reflect.M
6 import java.lang.reflect.M
7 import java.lang.reflect.ParameterizedT
8 import java.lang.reflect.T
9 import java.util.ArrayL
10 import java.util.C
11 import java.util.D
12 import java.util.L
14 import mons.beanutils.BeanU
15 import mons.beanutils.ConvertU
16 import mons.beanutils.PropertyU
17 import mons.beanutils.locale.converters.DateLocaleC
18 import mons.lang.StringU
19 import mons.logging.L
20 import mons.logging.LogF
21 import org.springframework.util.A
* 反射工具类.
* 提供访问私有变量,获取泛型类型Class, 提取集合中元素的属性, 转换字符串到对象等Util函数.
30 public class ReflectionUtil {
private static Log logger = LogFactory.getLog(ReflectionUtil.class);
DateLocaleConverter dc = new DateLocaleConverter();
// dc.setPatterns(new String[] { "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss" });
ConvertUtils.register(dc, Date.class);
* 调用Getter方法.
public static Object invokeGetterMethod(Object target, String propertyName) {
String getterMethodName = "get" + StringUtils.capitalize(propertyName);
return invokeMethod(target, getterMethodName, new Class[] {},
new Object[] {});
* 调用Setter方法.使用value的Class来查找Setter方法.
public static void invokeSetterMethod(Object target, String propertyName,
Object value) {
invokeSetterMethod(target, propertyName, value, null);
* 调用Setter方法.
* @param propertyType
用于查找Setter方法,为空时使用value的Class替代.
public static void invokeSetterMethod(Object target, String propertyName,
Object value, Class&?& propertyType) {
Class&?& type = propertyType != null ? propertyType : value.getClass();
String setterMethodName = "set" + StringUtils.capitalize(propertyName);
invokeMethod(target, setterMethodName, new Class[] { type },
new Object[] { value });
* 直接读取对象属性值, 无视private/protected修饰符, 不经过getter函数.
public static Object getFieldValue(final Object object,
final String fieldName) {
Field field = getDeclaredField(object, fieldName);
if (field == null) {
throw new IllegalArgumentException("Could not find field ["
+ fieldName + "] on target [" + object + "]");
makeAccessible(field);
Object result = null;
result = field.get(object);
} catch (IllegalAccessException e) {
logger.error("不可能抛出的异常{}" + e.getMessage());
* 直接设置对象属性值, 无视private/protected修饰符, 不经过setter函数.
public static void setFieldValue(final Object object,
final String fieldName, final Object value) {
Field field = getDeclaredField(object, fieldName);
100
if (field == null) {
102
throw new IllegalArgumentException("Could not find field ["
103
+ fieldName + "] on target [" + object + "]");
104
makeAccessible(field);
107
field.set(object, value);
110
} catch (IllegalAccessException e) {
111
logger.error("不可能抛出的异常:{}" + e.getMessage());
112
* 直接调用对象方法, 无视private/protected修饰符.
117
public static Object invokeMethod(final Object object,
119
final String methodName, final Class&?&[] parameterTypes,
120
final Object[] parameters) {
121
Method method = getDeclaredMethod(object, methodName, parameterTypes);
122
if (method == null) {
123
throw new IllegalArgumentException("Could not find method ["
124
+ methodName + "] parameterType " + parameterTypes
125
+ " on target [" + object + "]");
126
method.setAccessible(true);
129
return method.invoke(object, parameters);
132
} catch (Exception e) {
133
throw convertReflectionExceptionToUnchecked(e);
134
* 循环向上转型, 获取对象的DeclaredField.
139
* 如向上转型到Object仍无法找到, 返回null.
141
protected static Field getDeclaredField(final Object object,
143
final String fieldName) {
144
Assert.notNull(object, "object不能为空");
145
Assert.hasText(fieldName, "fieldName");
146
for (Class&?& superClass = object.getClass(); superClass != Object.class; superClass = superClass
147
.getSuperclass()) {
148
return superClass.getDeclaredField(fieldName);
150
} catch (NoSuchFieldException e) {// NOSONAR
151
// Field不在当前类定义,继续向上转型
152
return null;
155
* 强行设置Field可访问.
159
protected static void makeAccessible(final Field field) {
161
if (!Modifier.isPublic(field.getModifiers())
162
|| !Modifier.isPublic(field.getDeclaringClass().getModifiers())) {
163
field.setAccessible(true);
164
* 循环向上转型, 获取对象的DeclaredMethod.
169
* 如向上转型到Object仍无法找到, 返回null.
171
protected static Method getDeclaredMethod(Object object, String methodName,
173
Class&?&[] parameterTypes) {
174
Assert.notNull(object, "object不能为空");
175
for (Class&?& superClass = object.getClass(); superClass != Object.class; superClass = superClass
177
.getSuperclass()) {
178
return superClass.getDeclaredMethod(methodName, parameterTypes);
180
} catch (NoSuchMethodException e) {// NOSONAR
181
// Method不在当前类定义,继续向上转型
182
return null;
185
* 通过反射, 获得Class定义中声明的父类的泛型参数的类型. 如无法找到, 返回Object.class. eg. public UserDao
189
* extends HibernateDao&User&
190
* @param clazz
192
The class to introspect
193
* @return the first generic declaration, or Object.class if cannot be
194
determined
195
@SuppressWarnings("unchecked")
197
public static &T& Class&T& getSuperClassGenricType(final Class&?& clazz) {
198
return getSuperClassGenricType(clazz, 0);
199
* 通过反射, 获得定义Class时声明的父类的泛型参数的类型. 如无法找到, 返回Object.class.
203
* 如public UserDao extends HibernateDao&User,Long&
205
* @param clazz
207
clazz The class to introspect
208
* @param index
209
the Index of the generic ddeclaration,start from 0.
210
* @return the index generic declaration, or Object.class if cannot be
211
determined
212
@SuppressWarnings("unchecked")
214
public static Class getSuperClassGenricType(final Class&?& clazz,
215
final int index) {
216
Type genType = clazz.getGenericSuperclass();
217
if (!(genType instanceof ParameterizedType)) {
219
logger.warn(clazz.getSimpleName()
220
+ "'s superclass not ParameterizedType");
221
return Object.class;
222
Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
225
if (index &= params.length || index & 0) {
227
logger.warn("Index: " + index + ", Size of "
228
+ clazz.getSimpleName() + "'s Parameterized Type: "
229
+ params.length);
230
return Object.class;
231
if (!(params[index] instanceof Class)) {
233
logger.warn(clazz.getSimpleName()
234
+ " not set the actual class on superclass generic parameter");
235
return Object.class;
236
return (Class) params[index];
239
* 提取集合中的对象的属性(通过getter函数), 组合成List.
243
* @param collection
245
来源集合.
246
* @param propertyName
247
要提取的属性名.
248
public static List convertElementPropertyToList(
251
final Collection collection, final String propertyName) {
252
List list = new ArrayList();
253
for (Object obj : collection) {
256
list.add(PropertyUtils.getProperty(obj, propertyName));
257
} catch (Exception e) {
259
throw convertReflectionExceptionToUnchecked(e);
260
return
263
* 提取集合中的对象的属性(通过getter函数), 组合成由分割符分隔的字符串.
267
* @param collection
269
来源集合.
270
* @param propertyName
271
要提取的属性名.
272
* @param separator
273
分隔符.
274
@SuppressWarnings("unchecked")
276
public static String convertElementPropertyToString(
277
final Collection collection, final String propertyName,
278
final String separator) {
279
List list = convertElementPropertyToList(collection, propertyName);
280
return StringUtils.join(list, separator);
281
* 转换字符串到相应类型.
285
* @param value
287
待转换的字符串
288
* @param toType
289
转换目标类型
290
@SuppressWarnings("unchecked")
292
public static &T& T convertStringToObject(String value, Class&T& toType) {
293
return (T) ConvertUtils.convert(value, toType);
295
} catch (Exception e) {
296
throw convertReflectionExceptionToUnchecked(e);
297
* 将反射时的checked exception转换为unchecked exception.
302
public static RuntimeException convertReflectionExceptionToUnchecked(
304
Exception e) {
305
return convertReflectionExceptionToUnchecked(null, e);
306
public static RuntimeException convertReflectionExceptionToUnchecked(
309
String desc, Exception e) {
310
desc = (desc == null) ? "Unexpected Checked Exception." :
311
if (e instanceof IllegalAccessException
312
|| e instanceof IllegalArgumentException
313
|| e instanceof NoSuchMethodException) {
314
return new IllegalArgumentException(desc, e);
315
} else if (e instanceof InvocationTargetException) {
316
return new RuntimeException(desc,
317
((InvocationTargetException) e).getTargetException());
318
} else if (e instanceof RuntimeException) {
319
return (RuntimeException)
320
return new RuntimeException(desc, e);
322
public static final &T& T getNewInstance(Class&T& cls) {
325
return cls.newInstance();
327
} catch (InstantiationException e) {
328
e.printStackTrace();
329
} catch (IllegalAccessException e) {
330
e.printStackTrace();
331
return null;
333
* 拷贝 source 指定的porperties 属性 到 dest中
337
* @return void
339
* @throws InvocationTargetException
340
* @throws IllegalAccessException
341
public static void copyPorperties(Object dest, Object source,
343
String[] porperties) throws InvocationTargetException,
344
IllegalAccessException {
345
for (String por : porperties) {
346
Object srcObj = invokeGetterMethod(source, por);
347
logger.debug("属性名:" + por + "------------- 属性值:" + srcObj);
348
if (srcObj != null) {
349
BeanUtils.setProperty(dest, por, srcObj);
351
} catch (IllegalArgumentException e) {
352
e.printStackTrace();
353
} catch (IllegalAccessException e) {
354
} catch (InvocationTargetException e) {
356
* 两者属性名一致时,拷贝source里的属性到dest里
364
* @return void
366
* @throws IllegalAccessException
367
* @throws InvocationTargetException
368
public static void copyPorperties(Object dest, Object source)
371
throws IllegalAccessException, InvocationTargetException {
372
Class&? extends Object& srcCla = source.getClass();
373
Field[] fsF = srcCla.getDeclaredFields();
374
for (Field s : fsF) {
376
String name = s.getName();
377
Object srcObj = invokeGetterMethod(source, name);
378
BeanUtils.setProperty(dest, name, srcObj);
380
} catch (IllegalArgumentException e) {
381
e.printStackTrace();
382
} catch (IllegalAccessException e) {
383
} catch (InvocationTargetException e) {
385
// BeanUtils.copyProperties(dest, orig);
389
public static void main(String[] args) throws InvocationTargetException,
392
IllegalAccessException {
393
* Document document = new Document(); document.setId(2);
395
* document.setCreateDate(new Date()); DocumentVo dcoVo = new
396
* DocumentVo(); ReflectionUtils.copyPorperties(dcoVo, document,new
397
* String[]{"id","businessName","createDate","applyName","docTitle",
398
* "transactStatus"}); System.out.println(dcoVo.getId());
399
View Code
此外,导出到文件时,还用到了一个读写文件的工具类:
1 package blogs.yjmyzz.
3 import java.io.*;
4 import java.util.*;
5 import java.util.concurrent.*;
* 文件处理辅助类
* @version 0.2
15 public class FileUtil {
* 当前目录路径
public static String currentWorkDir = System.getProperty("user.dir") + "\\";
* @param str
* @param length
* @param ch
public static String leftPad(String str, int length, char ch) {
if (str.length() &= length) {
char[] chs = new char[length];
Arrays.fill(chs, ch);
char[] src = str.toCharArray();
System.arraycopy(src, 0, chs, length - src.length, src.length);
return new String(chs);
* 删除文件
* @param fileName
待删除的完整文件名
public static boolean delete(String fileName) {
boolean result = false;
File f = new File(fileName);
if (f.exists()) {
result = f.delete();
result = true;
* 递归获取指定目录下的所有的文件(不包括文件夹)
* @param obj
public static ArrayList&File& getAllFiles(String dirPath) {
File dir = new File(dirPath);
ArrayList&File& files = new ArrayList&File&();
if (dir.isDirectory()) {
File[] fileArr = dir.listFiles();
for (int i = 0; i & fileArr. i++) {
File f = fileArr[i];
if (f.isFile()) {
files.add(f);
files.addAll(getAllFiles(f.getPath()));
* 获取指定目录下的所有文件(不包括子文件夹)
* @param dirPath
public static ArrayList&File& getDirFiles(String dirPath) {
File path = new File(dirPath);
File[] fileArr = path.listFiles();
ArrayList&File& files = new ArrayList&File&();
for (File f : fileArr) {
if (f.isFile()) {
files.add(f);
100
return
103
* 获取指定目录下特定文件后缀名的文件列表(不包括子文件夹)
107
* @param dirPath
109
目录路径
110
* @param suffix
111
文件后缀
112
* @return
113
public static ArrayList&File& getDirFiles(String dirPath,
115
final String suffix) {
116
File path = new File(dirPath);
117
File[] fileArr = path.listFiles(new FilenameFilter() {
118
public boolean accept(File dir, String name) {
119
String lowerName = name.toLowerCase();
120
String lowerSuffix = suffix.toLowerCase();
121
if (lowerName.endsWith(lowerSuffix)) {
122
return true;
123
return false;
125
ArrayList&File& files = new ArrayList&File&();
129
for (File f : fileArr) {
131
if (f.isFile()) {
132
files.add(f);
133
return
136
* 读取文件内容
140
* @param fileName
142
待读取的完整文件名
143
* @return 文件内容
144
* @throws IOException
145
public static String read(String fileName) throws IOException {
147
File f = new File(fileName);
148
FileInputStream fs = new FileInputStream(f);
149
String result = null;
150
byte[] b = new byte[fs.available()];
151
fs.read(b);
152
fs.close();
153
result = new String(b);
154
return
155
* 写文件
159
* @param fileName
161
目标文件名
162
* @param fileContent
163
写入的内容
164
* @return
165
* @throws IOException
166
public static boolean write(String fileName, String fileContent)
168
throws IOException {
169
return write(fileName, fileContent, true, true);
170
* 写文件
174
* @param fileName
176
完整文件名(类似:/usr/a/b/c/d.txt)
177
* @param fileContent
178
文件内容
179
* @param autoCreateDir
180
目录不存在时,是否自动创建(多级)目录
181
* @param autoOverWrite
182
目标文件存在时,是否自动覆盖
183
* @return
184
* @throws IOException
185
public static boolean write(String fileName, String fileContent,
187
boolean autoCreateDir, boolean autoOverwrite) throws IOException {
188
return write(fileName, fileContent.getBytes(), autoCreateDir,
189
autoOverwrite);
190
* 写文件
194
* @param fileName
196
完整文件名(类似:/usr/a/b/c/d.txt)
197
* @param contentBytes
198
文件内容的字节数组
199
* @param autoCreateDir
200
目录不存在时,是否自动创建(多级)目录
201
* @param autoOverWrite
202
目标文件存在时,是否自动覆盖
203
* @return
204
* @throws IOException
205
public static boolean write(String fileName, byte[] contentBytes,
207
boolean autoCreateDir, boolean autoOverwrite) throws IOException {
208
boolean result = false;
209
if (autoCreateDir) {
210
createDirs(fileName);
211
if (autoOverwrite) {
213
delete(fileName);
214
File f = new File(fileName);
216
FileOutputStream fs = new FileOutputStream(f);
217
fs.write(contentBytes);
218
fs.flush();
219
fs.close();
220
result = true;
221
return
222
* 追加内容到指定文件
226
* @param fileName
228
* @param fileContent
229
* @return
230
* @throws IOException
231
public static boolean append(String fileName, String fileContent)
233
throws IOException {
234
boolean result = false;
235
File f = new File(fileName);
236
if (f.exists()) {
237
RandomAccessFile rFile = new RandomAccessFile(f, "rw");
238
byte[] b = fileContent.getBytes();
239
long originLen = f.length();
240
rFile.setLength(originLen + b.length);
241
rFile.seek(originLen);
242
rFile.write(b);
243
rFile.close();
244
result = true;
246
return
247
* 拆分文件
251
* @param fileName
253
待拆分的完整文件名
254
* @param byteSize
255
按多少字节大小拆分
256
* @return 拆分后的文件名列表
257
* @throws IOException
258
public List&String& splitBySize(String fileName, int byteSize)
260
throws IOException {
261
List&String& parts = new ArrayList&String&();
262
File file = new File(fileName);
263
int count = (int) Math.ceil(file.length() / (double) byteSize);
264
int countLen = (count + "").length();
265
ThreadPoolExecutor threadPool = new ThreadPoolExecutor(count,
266
count * 3, 1, TimeUnit.SECONDS,
267
new ArrayBlockingQueue&Runnable&(count * 2));
268
for (int i = 0; i & i++) {
270
String partFileName = file.getPath() + "."
271
+ leftPad((i + 1) + "", countLen, '0') + ".part";
272
threadPool.execute(new SplitRunnable(byteSize, i * byteSize,
273
partFileName, file));
274
parts.add(partFileName);
275
return
277
* 合并文件
281
* @param dirPath
283
拆分文件所在目录名
284
* @param partFileSuffix
285
拆分文件后缀名
286
* @param partFileSize
287
拆分文件的字节数大小
288
* @param mergeFileName
289
合并后的文件名
290
* @throws IOException
291
public void mergePartFiles(String dirPath, String partFileSuffix,
293
int partFileSize, String mergeFileName) throws IOException {
294
ArrayList&File& partFiles = FileUtil.getDirFiles(dirPath,
295
partFileSuffix);
296
Collections.sort(partFiles, new FileComparator());
297
RandomAccessFile randomAccessFile = new RandomAccessFile(mergeFileName,
299
"rw");
300
randomAccessFile.setLength(partFileSize * (partFiles.size() - 1)
301
+ partFiles.get(partFiles.size() - 1).length());
302
randomAccessFile.close();
303
ThreadPoolExecutor threadPool = new ThreadPoolExecutor(
305
partFiles.size(), partFiles.size() * 3, 1, TimeUnit.SECONDS,
306
new ArrayBlockingQueue&Runnable&(partFiles.size() * 2));
307
for (int i = 0; i & partFiles.size(); i++) {
309
threadPool.execute(new MergeRunnable(i * partFileSize,
310
mergeFileName, partFiles.get(i)));
311
* 根据文件名,比较文件
317
private class FileComparator implements Comparator&File& {
322
public int compare(File o1, File o2) {
323
return o1.getName().compareToIgnoreCase(o2.getName());
324
* 创建(多级)目录
329
* @param filePath
331
完整的文件名(类似:/usr/a/b/c/d.xml)
332
public static void createDirs(String filePath) {
334
File file = new File(filePath);
335
File parent = file.getParentFile();
336
if (parent != null && !parent.exists()) {
337
parent.mkdirs();
338
* 分割处理Runnable
344
private class SplitRunnable implements Runnable {
349
int byteS
350
String partFileN
351
File originF
352
int startP
353
public SplitRunnable(int byteSize, int startPos, String partFileName,
355
File originFile) {
356
this.startPos = startP
357
this.byteSize = byteS
358
this.partFileName = partFileN
359
this.originFile = originF
360
public void run() {
363
RandomAccessFile rF
364
OutputS
365
rFile = new RandomAccessFile(originFile, "r");
367
byte[] b = new byte[byteSize];
368
rFile.seek(startPos);// 移动指针到每&段&开头
369
int s = rFile.read(b);
370
os = new FileOutputStream(partFileName);
371
os.write(b, 0, s);
372
os.flush();
373
os.close();
374
} catch (IOException e) {
375
e.printStackTrace();
376
* 合并处理Runnable
382
private class MergeRunnable implements Runnable {
387
long startP
388
String mergeFileN
389
File partF
390
public MergeRunnable(long startPos, String mergeFileName, File partFile) {
392
this.startPos = startP
393
this.mergeFileName = mergeFileN
394
this.partFile = partF
395
public void run() {
398
RandomAccessFile rF
399
rFile = new RandomAccessFile(mergeFileName, "rw");
401
rFile.seek(startPos);
402
FileInputStream fs = new FileInputStream(partFile);
403
byte[] b = new byte[fs.available()];
404
fs.read(b);
405
fs.close();
406
rFile.write(b);
407
rFile.close();
408
} catch (IOException e) {
409
e.printStackTrace();
410
View Code
最后是调用示例:
public void testExcel() throws Exception {
List&String[]& columNames = new ArrayList&String[]&();
columNames.add(new String[] { "运单号", "代理人" });
columNames.add(new String[] { "运单号", "代理人" });
List&String[]& fieldNames = new ArrayList&String[]&();
fieldNames.add(new String[] { "awbNumber", "agent" });
10
fieldNames.add(new String[] { "awbNumber", "agent" });
11
LinkedHashMap&String, List&?&& map = new LinkedHashMap&String, List&?&&();
13
map.put("运单月报(1月)", getData1());
14
map.put("运单月报(2月)", getData2());
15
ExcelExportData setInfo = new ExcelExportData();
18
setInfo.setDataMap(map);
19
setInfo.setFieldNames(fieldNames);
20
setInfo.setTitles(new String[] { "航空运单报表1","航空运单报表2"});
21
setInfo.setColumnNames(columNames);
22
// 将需要导出的数据输出到文件
24
System.out.println(ExcelUtil.export2File(setInfo, "r:/test.xls"));
25
View Code
导出后的样子如下:
本文标题:
本页链接:

我要回帖

更多关于 android 不要标题栏 的文章

 

随机推荐