poi import/export excel example

a simple example of import/export excel using java poi:

1. import excel

the excel is like:

Snap1

public String upldstd(){
InputStream is = null;
POIFSFileSystem fs = null;
try {
String selectpaper = getRequest().getParameter(“selectpaper”);
File selFile = ufForm.getQuestionfile()[0];
//read excel
is = new FileInputStream(selFile);
fs = new POIFSFileSystem(is);
Workbook wb = new HSSFWorkbook(fs);
HSSFSheet sheet = (HSSFSheet) wb.getSheetAt(0);
String[] exlacc = new String[sheet.getLastRowNum()];
HSSFRow row = null;
HSSFCell cell = null;
int index = 0;
for (int i = 1; i <= sheet.getLastRowNum(); i++) {
row = sheet.getRow(i);
cell = row.getCell(0);
if (cell != null) {
cell.setCellType(Cell.CELL_TYPE_STRING);
exlacc[index] = cell.getRichStringCellValue().toString();
System.out.println(exlacc[index]);
index = index + 1;
}
}
//check whether in the tb_user, remove those not in tb_user.
UserServ userServ = new UserServ();
Field field = new Field();
field.setIn(true);
field.setObjs(exlacc);
FieldsMap fieldsMap = new FieldsMap();
fieldsMap.putMap(“account”, field);
List<TbUser> uList = userServ.getUser(fieldsMap, null);
if (uList == null || uList.size() == 0) {
writeJson(“{success:” + false + “,msg:\”导入失败!未找到excel中指定的学员!\”}”);
return null;
}
String[] userids = new String[uList.size()];
for (int i = 0; i < uList.size(); i++) {
userids[i] = uList.get(i).getUserId();
System.out.println(userids[i]);
}
ExuserServ exuserServ = new ExuserServ();
//only save users not in tb_exuser
MultiFields multiFields = new MultiFields();
Field xField = new Field();
xField.setIn(true);
xField.setObjs(userids);
fieldsMap = new FieldsMap();
fieldsMap.putMap(“tbUser.userId”, xField);
multiFields.addFieldsMap(fieldsMap);
FieldsMap eFieldsMap = new FieldsMap();
eFieldsMap.putMap(“tbExam.eid”, selectpaper);
multiFields.addFieldsMap(eFieldsMap);
List<TbExuser> euList = exuserServ.getExuser(multiFields, null);
TbExam exam = new TbExam();
exam.setEid(selectpaper);
if (euList == null || euList.isEmpty()) {
List<TbExuser> saveList = new LinkedList<TbExuser>();
TbExuser exuser = null;
TbUser user = null;
for (int i = 0; i < userids.length; i++) {
exuser = new TbExuser();
exuser.setTbExam(exam);
user = new TbUser();
exuser.setTbUser(user);
saveList.add(exuser);
}
exuserServ.saveExuser(saveList);
}else if (euList.size() != userids.length) {
Set<String> euSet = new HashSet<String>();
for (int i = 0; i < euList.size(); i++) {
if (euList.get(i) != null && euList.get(i).getTbUser() != null) {
euSet.add(euList.get(i).getTbUser().getUserId());
}
}
List<TbExuser> saveList = new LinkedList<TbExuser>();
TbExuser exuser = null;
TbUser user = null;
for (int i = 0; i < userids.length; i++) {
if (!euSet.contains(userids[i])) {
exuser = new TbExuser();
exuser.setTbExam(exam);
user = new TbUser();
exuser.setTbUser(user);
saveList.add(exuser);
}
}
exuserServ.saveExuser(saveList);
}else {
System.out.println(“already in the list!”);
}
writeJson(“{success:” + true + “,msg:\”导入成功!\”}”);
} catch (Exception e) {
// TODO: handle exception
writeJson(“{success:” + false + “,msg:\”导入失败!\”}”);
e.printStackTrace();
} finally {
try {
if (is != null) {
is.close();
}
} catch (Exception e2) {
// TODO: handle exception
}
}
return null;
}

2. when the excel have special data

(percent, fraction, date)

percent(eg: 20%):

if (cell2.getCellStyle().getDataFormatString().indexOf(“%”) != -1) {
System.out.println(cell2.getNumericCellValue()*100+”%”);
}

date(eg: 10/28/2013):

cell2.getCellStyle().getDataFormatString()//m/d/yy or something like data format

Date date = DateUtil.getJavaDate(cell1.getNumericCellValue());

fraction(eg: 1/3):

DataFormatter formatter = new DataFormatter();
System.out.println(formatter.formatCellValue(cell1));

3. export excel

import org.apache.poi.hssf.usermodel.HSSFCell;
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.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.HSSFColor;
import org.apache.struts2.ServletActionContext;

/************
* export excel
* @param <T>
* @param title
* @param headers
* @param dataset
*/
@SuppressWarnings(“unchecked”)
protected<T> void exportExcel(String title,String[] headers,Collection<T> dataset){
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet(title);
sheet.setDefaultColumnWidth(15);

HSSFCellStyle style = workbook.createCellStyle();

style.setFillForegroundColor(HSSFColor.SKY_BLUE.index);
style.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
style.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style.setBorderLeft(HSSFCellStyle.BORDER_THIN);
style.setBorderRight(HSSFCellStyle.BORDER_THIN);
style.setBorderTop(HSSFCellStyle.BORDER_THIN);
style.setAlignment(HSSFCellStyle.ALIGN_CENTER);

HSSFFont font = workbook.createFont();
font.setColor(HSSFColor.VIOLET.index);
font.setFontHeightInPoints((short) 12);
font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);

style.setFont(font);

HSSFCellStyle style2 = workbook.createCellStyle();
style2.setFillForegroundColor(HSSFColor.WHITE.index);
style2.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND);
style2.setBorderBottom(HSSFCellStyle.BORDER_THIN);
style2.setBorderLeft(HSSFCellStyle.BORDER_THIN);
style2.setBorderRight(HSSFCellStyle.BORDER_THIN);
style2.setBorderTop(HSSFCellStyle.BORDER_THIN);
style2.setAlignment(HSSFCellStyle.ALIGN_CENTER);
style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);

HSSFFont font2 = workbook.createFont();
font2.setBoldweight(HSSFFont.BOLDWEIGHT_NORMAL);

style2.setFont(font2);

HSSFRow row = sheet.createRow(0);
HSSFCell cell = null;
HSSFRichTextString text = null;
for (int i = 0; i < headers.length; i++) {
cell = row.createCell(i);
cell.setCellStyle(style);
text = new HSSFRichTextString(headers[i]);
cell.setCellValue(text);
}

//单元格合并

HSSFRow row = sheet.createRow(0);
HSSFCell cell = row.createCell(0);
cell.setCellValue(exam.getEtitle() + ” 缺考人员名单”);
cell.setCellStyle(headstyle);
sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 1));

Iterator<?> iterator = dataset.iterator();
int index = 0;
while (iterator.hasNext()) {
index++;
row = sheet.createRow(index);
T t = (T) iterator.next();
Field[] fields = t.getClass().getDeclaredFields();
for (int j = 0; j < fields.length; j++) {
cell = row.createCell(j);
cell.setCellStyle(style2);
String fieldName = fields[j].getName();
String getMethodName = “get” + fieldName.substring(0,1).toUpperCase() + fieldName.substring(1);
try {
Class tcls = t.getClass();
Method getMethod = tcls.getMethod(getMethodName, new Class[] {});
Object value = getMethod.invoke(t, new Object[] {});
String textvalue = “”;
if (value != null) {
textvalue = value.toString();
}
text = new HSSFRichTextString(textvalue);
cell.setCellValue(text);
} catch (Exception e) {
// TODO: handle exception
logger.error(e.toString());
}
}
}
OutputStream out = null;
try {
HttpServletResponse response = getResponse();
response.reset();
response.setContentType(“APPLICATION/x-msdownload”);
response.addHeader(“Content-Disposition”, “attachment;filename=\””
+ new String((title + “.xls”).getBytes(“GBK”),
“ISO8859_1”) + “\””);
out = response.getOutputStream();
out.flush();
workbook.write(out);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
logger.error(e.toString());
} finally {
try {
out.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

//reference:

1. http://blog.csdn.net/lenolong/article/details/3957735
2. http://wenku.baidu.com/view/20268edfce2f0066f533222e.html
3. http://wenku.baidu.com/view/93130dcca1c7aa00b52acb75.html

This entry was posted in Computer, Java. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s