2013年12月13日星期五

We love to share ---- Excel POI3.6

Because every time you send a limited amount of code, so one can only send a little , I hope you first do not reply , thank you.

There are so many information :
BaseBean.java
TitleBean.java
EntityBean.java
ExcelConstant.java
ExcelEditor.java
PropertyUtil.java
UserInfoBean.java
ExcelDemo.java

userinfo.xls
UserInfoBean_ch.properties
UserInfoBean.properties



------ Solution ------------------------------------ --------
recommended
------ Solution --------------------------- -----------------
Thank LZ share .!
------ Solution ------------- -------------------------------
LZ continue ! ! !
------ Solution ---------------------------------------- ----
ah this example, the operation of reading on the POI should be familiar !
------ Solution --------------- -----------------------------
good stuff , thank you for sharing .
------ Solution ---------------------------------------- ----
read about POI Excel if you encounter a complex situation if , in fact, very bad deal . For example , there is a small compartment peers count of class


Excel when writing , especially across Subtotal ( Total ) these problems, to utilize List Map these existing data structures.
------ Solution ---------------------------------------- ----
good stuff , thank you for sharing .
------ Solution ---------------------------------------- ----
Well, to tell you an example of the idea to write Excel


look at this picture . . If this is the structure of Excel ( written out ) , if the deal ?

First, define a Bean, comprising: a department name, title , address, that is, all of the header

Second, identify the data, in all sectors to join Set
Third, the definition of a Map > structure to store management data. string type of key that is the department name , list is this part of the sector Bean>

We found this structure to use when writing Excel , you just like to iterate on Map . First, you want to merge the departments that column cells , is not it? How many combined ranks ? You can map , gets his data list.size () so you know how much okay to merge

So, scalability is also particularly good. Even add more departments do not need to change the program .


Of course , there are more complex Excel, you can adopt at this idea, they used a more complex structure to store data . . In short , flexible with good Set, List, Map, will let you operate Excel, handy.
------ Solution ------------------------------------ --------

------ Solution ---------------------------------------- ----
Yes, the top one
------ Solution ----------------------------- ---------------

------ Solution --------------------------------- -----------
mark ..
------ Solution ----------------------- ---------------------
very good ! From the top . . . . . .
------ Solution ---------------------------------------- ----
so much code looks dizzy.
------ Solution ---------------------------------------- ----
Thank you for sharing
------ Solution ------------------------- -------------------
reading program , tired, do not know ~ ~ ~
------ Solution ------ under --------------------------------------
learning , good, thank you lz
------ Solution ------------------------------------------ -
I do not understand ah bleeding and
------ Solution ----------------- ---------------------------
good collection.
------ Solution ---------------------------------------- ----
good collection .
------ Solution ---------------------------------------- ----
familiar POI operating EXCEL ~

Thank LZ!
------ Solution ---------------------------------------- ----
Thanks for sharing
------ Solution ------------------------------- -------------
Thank you for sharing
------ Solution ---------------------- ----------------------
win, not to vent
------ Solution ---------- ----------------------------------
or packaged upload dizzy watching it ~ ~
------ Solution - -------------------------------------------
**
* The UserInfoBean class contains all the user info.
* /
public class UserInfoBean implements EntityBean {
private String username;

private String password;

private String role;

private String type;

private String regTime;

private Map dynamicInfo;

public UserInfoBean () {
dynamicInfo = new LinkedHashMap ();
}

/ **
* @ return the password
* /
public String getPassword () {
return password;
}

/ **
* @ param password the password to set
* /
public void setPassword (String password) {
this.password = password;
}

/ **
* @ return the type
* /
public String getType () {
return type;
}

/ **
* @ param type the type to set
* /
public void setType (String type) {
this.type = type;
}

/ **
* @ return the regTime
* /
public String getRegTime () {
return regTime;
}

/ **
* @ param regTime the regTime to set
* /
public void setRegTime (String regTime) {
this.regTime = regTime;
}

/ **
* @ return the role
* /
public String getRole () {
return role;
}

/ **
* @ param role the role to set
* /
public void setRole (String role) {
this.role = role;
}

/ **
* @ return the username
* /
public String getUsername () {
return username;
}

/ **
* @ param username the username to set
* /
public void setUsername (String username) {
this.username = username;
}

public String getClsName () {
return getClass () getName ().;
}

public String getClsSimpleName () {
return getClass () getSimpleName ().;
}

public String getSheetName () {
return "userinfo";
}

public String getTableName () {
return "USER_INFO";
}

public void putDynamicInfo (String title, Object value) {
dynamicInfo.put (title, value);
}

public Map getDynamicInfo () {
return dynamicInfo;
}

public String toString () {
StringBuffer string = new StringBuffer ();
string.append ("username =" + getUsername ());
string.append (", password =" + getPassword ());
string.append (", role =" + getRole ());
string.append (", purview =" + getType ());
string.append (", regTime =" + getRegTime ());

return string.toString ();
}
}


------ Solution ------------------------------------ --------
dizziness
------ Solution - -------------------------------------------
/ / mark for dynamic title, such as month.
else if (title == null) {
title = ; ExcelConstant.DYNAMIC_COLUMN + val;
titleBean.put ( title);
}
else {
if (importColsList ! = null && importColsList.contains (title)) {
titleBean.put (title);
}
else {
titleBean.put (title);
}
}

matter how this section
inside the if else doing exactly the same ah
------ Solution ----------------------- ---------------------
ONKANBU
------ Solution --------------- -----------------------------
observe the advanced achievements
------ Solution ----- ---------------------------------------
learn ! !
------ Solution ---------------------------------------- ----
good collection next !
------ Solution ---------------------------------------- ----
mark .. standby
------ Solution -------------------------- ------------------
access points ,
------ Solution -------------- ------------------------------
Jie Feng Jie Feng gone gone gone Jie Feng Jie Feng Jie Feng gone gone gone Jie Feng the
------ Solution --------------------------------------- -----
Jie Feng Jie Feng gone gone gone Jie Feng Jie Feng gone
------ Solution -------------------- ------------------------
the way soon , if there is a password excel , poi how to access .
------ Solution ---------------------------------------- ----
good. Stuff.
------ Solution ---------------------------------------- ----
first met the future holds school
------ Solution ---------------------- ----------------------


like this one, the idea is very clear.
------ Solution ---------------------------------------- ----
I usually involves the use of EXCEL jxl.jar package operations are processed . But the idea should be the same .
------ Solution ---------------------------------------- ----
upstairs do not know the answer to the last puzzle cattle that he is also the top of a picture Conan Although poi played in dealings with the
----- N - For reference only ---------------------------------------

/**
 * The BaseBean interface will be implemented by all the beans.
 */
public interface BaseBean {
}

/**
 * The EntityBean interface will be implements by all the bean which has the
 * meanings.
 */
public interface EntityBean extends BaseBean {
   public String getClsName();
   
   public String getClsSimpleName();
   
   public String getSheetName();
   
   public String getTableName();
   
   public void putDynamicInfo(String title, Object value);
   
   public Map<String, Object> getDynamicInfo();
}

/**
 * The ExcelConstant class contains some constant variable.
 */
public final class ExcelConstant {
   public static final String DYNAMIC = "DYNAMIC";
   public static final String DYNAMIC_DATA = "DYNAMIC_DATA";
   public static final String DYNAMIC_COLUMN = "DYNAMIC_COLUMN";
}
< br> ------ For reference only ---------------------------------------

/**
 * The TitleBean class contains all the title of 
 * the excel sheet or the special table.
 */
public class TitleBean implements BaseBean {
   private LinkedList<String> titleList = new LinkedList<String>();

   private String beanName;

   public TitleBean() {
   }

   public void put(int index, String title) {
      titleList.add(index, title);
   }

   public void put(String title) {
      titleList.add(title);
   }

   public String get(int index) {
      return titleList.get(index);
   }

   public int size() {
      return titleList.size();
   }

   public LinkedList<String> getTitleList() {
      return titleList;
   }

   public void setTitleList(LinkedList<String> titleList) {
      this.titleList = titleList;
   }

   public String getBeanName() {
      return beanName;
   }

   public void setBeanName(String beanName) {
      this.beanName = beanName;
   }

   public boolean contains(Object obj) {
      return titleList.contains(obj);
   }

   public Iterator<String> iterator() {
      return titleList.iterator();
   }

   public void addFirst(String title) {
      titleList.addFirst(title);
   }

   public void remove(Object key) {
      titleList.remove(key);
   }

   public void remove(int index) {
      titleList.remove(index);
   }

   public String toString() {
      StringBuffer title = new StringBuffer();

      for(int i = 0; i < titleList.size(); i++) {
         title.append(titleList.get(i) + "\t");
      }

      return title.toString();
   }
}

------ For reference only -------------------------------- -------

/**
 * The PropertyUtil class store all the properties files info to memory.
 */
public class PropertyUtil {
   private static Properties prop;

   /**
    * @return which contains all the properties files's info.
    */
   public static Properties getProperties() {
      if(prop != null) {
         return prop;
      }

      prop = new Properties();

      try {
         prop.load(PropertyUtil.class
               .getResourceAsStream("UserInfoBean.properties"));
      }
      catch(Exception e) {
         e.printStackTrace();
      }

      return prop;
   }

   /**
    * The method return the value by the key from properties file,
    * if the value is null, return the key.
    * 
    * @param key the special key.
    * @return the value mapping the key.
    */
   public static String getProperty(String key) {
      String val = key == null ? null : getProperties().getProperty(key);
      return val != null ? val : (key == null ? "NULL" : key);
   }

   /**
    * The method check if exist key value in properties file.
    * 
    * @param key the special key.
    * @return the value mapping the key.
    */
   public static String getProperty2(String key) {
      return getProperties().getProperty(key);
   }
}

------ For reference only ------------------------- --------------
ExcelEditor.java


import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.poifs.filesystem.OfficeXmlFileException;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

/**
 * The ExcelEditor class provide some methods to read from excel file, 
 * or write into excel file.
 */
public class ExcelEditor {
   public static Map<EntityBean, List<BaseBean>> readExcel(File excel,
         EntityBean[] beans, List<String> importColsList) throws Exception {
      return readExcel(excel, beans, importColsList, false);
   }

   /**
    * The method is used to read excel file. 
    * it can read one sheet or one more sheet, 
    * that rest with the bean's number.
    * 
    * @param excel The file which read from.
    * @param beans Which's construct as same as the excel sheet.
    * @return sheetBean The map<sheet name, List<BaseBean>>;
    * @throws IOException
    */
   public static Map<EntityBean, List<BaseBean>> readExcel(File excel,
         EntityBean[] beans, List<String> importColsList, 
         boolean allDynamic) throws Exception {
      Map<EntityBean, List<BaseBean>> sheetBean = 
         new HashMap<EntityBean, List<BaseBean>>();
      InputStream in = new FileInputStream(excel);
      Workbook book = null;

      try {
         book = new HSSFWorkbook(in);
      }
      catch(OutOfMemoryError e) {
         String msg = "The file " + excel.getName()
               + " data is error, please delete invalid data!";

         throw new Exception(msg);
      }
      catch(OfficeXmlFileException e) {
         in = new FileInputStream(excel);
         book = new XSSFWorkbook(in);
      }
      
      if(book == null || book.getNumberOfSheets() == 0) {
         return sheetBean;
      }

      // read more than one sheet.
      for(int sheetNum = 0; sheetNum < book.getNumberOfSheets(); sheetNum++) {
         Sheet sheet = book.getSheetAt(sheetNum);

         if(sheetNum > 0) {
            in.close();

            return sheetBean;
         }

         if(sheet == null || sheet.getLastRowNum() == 0) {
            throw new Exception("data.not.found");
         }

         for(int i = 0; i < beans.length; i++) {
            if(sheet.getSheetName() != "") {
               sheetBean.put(beans[i],
                     readExcelSheet(sheet, beans[i], importColsList, allDynamic));
            }
         }
      }

      in.close();

      return sheetBean;
   }

------ For reference only ----------------------------------- ----
help you off the floor it ~
------ For reference only ------------------------- --------------

   /**
    * The method read excel sheet data into list.
    * 
    * @param sheet excel sheet.
    * @param bean which store the sheet data.
    * @param prop resource obj.
    * @param importColsList which contains which column should import.
    * @return list contains sheet data.
    * @throws Exception
    */
   public static List<BaseBean> readExcelSheet(Sheet sheet,
         EntityBean bean, List<String> importColsList, 
         boolean allDynamic) throws Exception {
      List<BaseBean> beanList = new ArrayList<BaseBean>();
      if(sheet == null || sheet.getLastRowNum() == 0) {
         return beanList;
      }

      try {
         Class<?> cls = Class.forName(bean.getClsName());
         TitleBean titleBean = new TitleBean();
         boolean hasTitle = false;
         int titleRow = 0;
         Object stringType = msg(bean.getClsSimpleName() + "_" + "string");
         List<String> stringTypeField = 
            stringType == null ?  new ArrayList<String>() : 
               Arrays.asList(String.valueOf(stringType).split(","));

         for(int rowNum = 0; rowNum <= sheet.getLastRowNum(); rowNum++) {
            Row row = sheet.getRow(rowNum);

            if(row == null || row.getLastCellNum() == 0) {
               continue;
            }

            EntityBean obj = (EntityBean) cls.newInstance();

            for(int cellNum = 0; cellNum < row.getLastCellNum(); cellNum++) {
               Cell cell = row.getCell(cellNum);

               if(cell == null) {
                  continue;
               }

               if(!hasTitle) {
                  String val = null;

                  switch(cell.getCellType()) {
                     case HSSFCell.CELL_TYPE_STRING:
                        val = cell.getStringCellValue();
                        break;
                     case HSSFCell.CELL_TYPE_NUMERIC:
                        val = String.valueOf(cell.getNumericCellValue());
                        break;
                     default:
                        val = "";
                        break;
                  }

------ For reference only ------------------ ---------------------

                  String title = PropertyUtil.getProperty2(
                        obj.getClsSimpleName() + "_" + val.trim());

                  // int lookMaterByBoard or lookBoardByMater,
                  // we should append other column except code.
                  // the other column maybe exist in the material or board object,
                  // so the value will be set in the set method,
                  // but we use dynamicInfo when output the other column,
                  // so the exsit column will not in the dynamicInfo,
                  // here we make all the other column dynamic.
                  if(allDynamic && cellNum != 0 && title!= null) {
                     title = null;
                  }

                  // skip the invalid row.
                  if(cellNum == 0 && title == null) {
                     break;
                  }
                  // mark for dynamic title, such as month.
                  else if(title == null) {
                     title = ExcelConstant.DYNAMIC_COLUMN + val;
                     titleBean.put(title);
                  }
                  else {
                     if(importColsList != null && importColsList.contains(title)) {
                        titleBean.put(title);
                     }
                     else {
                        titleBean.put(title);
                     }
                  }

                  if(cellNum == row.getLastCellNum() - 1) {
                     titleBean.setBeanName(obj.getClsSimpleName());
                     beanList.add(titleBean);
                     hasTitle = true;
                     titleRow = rowNum;
                  }
               }
               else {
                  String name = titleBean.get(cellNum);
                  
                  if(name == null || "".equals(name.trim())) {
                     continue;
                  }

                  int index = name.indexOf(ExcelConstant.DYNAMIC);

                  if(index != -1) {
                     Method method = cls.getMethod("putDynamicInfo",
                           String.class, Object.class);
                     String dTitle = name;

                     switch(cell.getCellType()) {
                        case HSSFCell.CELL_TYPE_STRING:
                           method.invoke(obj, new Object[] {dTitle,
                                 cell.getStringCellValue().trim()});
                           break;
                        case HSSFCell.CELL_TYPE_NUMERIC:
                           if(HSSFDateUtil.isCellDateFormatted(cell)) {
                              Timestamp t = new Timestamp(
                                    cell.getDateCellValue().getTime());
                              method.invoke(obj, new Object[] {dTitle, t});
                           }
                           else {
                              method.invoke(obj, new Object[] {dTitle,
                                    cell.getNumericCellValue()});
                           }

                           break;
                        default:
                           break;
                     }

                     continue;
                  }

                  Field field = null;
                  String fieldName = null;
                  String methodName = null;

------ For reference only ----------- ----------------------------

                  try {
                     try {
                        field = cls.getDeclaredField(name);
                     }
                     catch(NoSuchFieldException e) {
                        field = cls.getField(name);
                     }

                     fieldName = field.getName();
                     methodName = "set" + toFirstUpperCase(fieldName);
                     Method method = cls.getMethod(methodName, field.getType());

                     switch(cell.getCellType()) {
                        case HSSFCell.CELL_TYPE_STRING:
                           method.invoke(obj, new Object[] {cell
                                 .getStringCellValue().trim()});

                           break;
                        case HSSFCell.CELL_TYPE_NUMERIC:
                           if(HSSFDateUtil.isCellDateFormatted(cell)) {
                              SimpleDateFormat format = 
                                 new SimpleDateFormat("yyyy-MM-dd");
                              String d = format.format(
                                 new Date(cell.getDateCellValue().getTime()));
                              method.invoke(obj, new Object[] {d});
                           }
                           else {
                              Double d = cell.getNumericCellValue();
                              DecimalFormat df = new DecimalFormat();
                              df.applyPattern("0");

                              if(stringTypeField.contains(fieldName)) {
                                 method.invoke(obj, new Object[] {String.valueOf(d)});
                              }
                              else {
                                 method.invoke(obj, new Object[] {
                                       d.intValue()});
                              }
                           }

                           break;
                        default:
                           break;
                     }
                  }
                  catch(Exception e) {
                     e.printStackTrace();
                  }
               }
            }

            if(rowNum > titleRow 
                  && hasTitle 
                  && row.getCell(0) != null 
                  && row.getCell(0).getCellType() != Cell.CELL_TYPE_BLANK) {
               beanList.add(obj);
            }
         }

         if(!hasTitle) {
            throw new Exception("excel.title.error");
         }
      }
      catch(Exception e) {
         e.printStackTrace();
      }

      return beanList;
   }

------ For reference only ---- -----------------------------------
NND can only send three consecutive times . Who saw me three times to reply , thank you .

   /**
    * THe method write common data into excel.
    * 
    * @param out output stream.
    * @param beanList which contains common data.
    * @throws Exception
    */
   @SuppressWarnings("unchecked")
   public static void writeExcel(OutputStream out, List<BaseBean> beanList)
         throws Exception {
      HSSFWorkbook book = new HSSFWorkbook();
      HSSFDataFormat format = book.createDataFormat();
      HSSFCellStyle textStyle = book.createCellStyle();
      textStyle.setDataFormat(format.getFormat("@"));

      TitleBean title = null;
      HSSFSheet sheet = null;
      boolean isNewSheet = true;

      for(int i = 0; i < beanList.size(); i++) {
         if(beanList.get(i) instanceof TitleBean) {
            title = (TitleBean) beanList.get(i);
            continue;
         }

         EntityBean bean = (EntityBean) beanList.get(i);

         if(sheet != null && bean.getSheetName().equals(sheet.getSheetName())) {
            isNewSheet = false;
         }
         else {
            isNewSheet = true;
         }

         if(isNewSheet) {
            isNewSheet = false;
            if(bean.getSheetName() == null) {
               throw new Exception("sheet.name.is.null");
            }

            sheet = book.createSheet(bean.getSheetName());
            HSSFRow titleRow = sheet.createRow(sheet.getLastRowNum());

            for(int j = 0; title != null && j < title.size(); j++) {
               HSSFCell cell = titleRow.createCell(j);
               String t = "";
               int index = title.get(j).indexOf(ExcelConstant.DYNAMIC);

               if(index != -1) {
                  t = title.get(j).replace(ExcelConstant.DYNAMIC_COLUMN, "");
                  t = t.replace(ExcelConstant.DYNAMIC_DATA, "");
                  t = msg(t);
               }
               else {
                  t = msg(title.getBeanName() + "_"
                        + title.get(j));
               }

               cell.setCellValue(t);
               sheet.setColumnWidth(j, 3000);
            }
         }

         if(sheet == null || bean == null) {
            return;
         }

         HSSFRow row = sheet.createRow(sheet.getLastRowNum() + 1);

         for(int k = 0; k < title.size(); k++) {
            HSSFCell cell = row.createCell(k);
            int index = title.get(k).indexOf(ExcelConstant.DYNAMIC);

            if(index != -1) {
               Method method = bean.getClass().getMethod("getDynamicInfo");
               Map<String, Object> dynamicInfo = (Map<String, Object>) method.invoke(bean);
               String t = title.get(k).replace(ExcelConstant.DYNAMIC_DATA, "");
               Object obj = dynamicInfo.get(t);
               obj = obj == null ? "" : obj;

               try {
                  cell.setCellValue(Double.parseDouble(String.valueOf(obj)));
               }
               catch(NumberFormatException e) {
                  cell.setCellValue(String.valueOf(obj));
                  cell.setCellStyle(textStyle);
               }

               continue;
            }

------ For reference only ----------------------------------- ----

String methodName = "get" + toFirstUpperCase(title.get(k));

            try {
               Method method = bean.getClass().getMethod(methodName);
               Object obj = method.invoke(bean);

               if(obj instanceof String) {
                  if(methodName.indexOf("Code") != -1 
                        || "replacerMater".equals(title.get(k))) {
                     cell.setCellValue(String.valueOf(obj));
                     cell.setCellStyle(textStyle);
                  }
                  else {
                     try {
                        cell.setCellValue(Double.parseDouble(String.valueOf(obj)));
                     }
                     catch(NumberFormatException e) {
                        cell.setCellValue(String.valueOf(obj));
                        cell.setCellStyle(textStyle);
                     }
                  }
               }
               else if(obj instanceof Number) {
                  cell.setCellValue(Double.valueOf(String.valueOf(obj)));
               }
               else if(obj instanceof Date) {
                  HSSFCellStyle cs = book.createCellStyle();
                  cs.setDataFormat((short) 14);
                  cell.setCellStyle(cs);
                  cell.setCellValue(HSSFDateUtil.getExcelDate((Date) obj));
               }
               else if(obj instanceof Boolean) {
                  cell.setCellValue((Boolean) obj);
               }
               else if(obj == null) {
                  continue;
               }
               else {
                  throw new Exception("The " + obj + "'s type is error!");
               }
            }
            catch(NoSuchMethodException e) {
               throw new Exception("No such method: " + methodName);
            }
         }
      }

      book.write(out);
   }

   private static String toFirstUpperCase(String fieldName) {
      if(fieldName == null || fieldName.length() == 0) {
         return "";
      }
      else {
         return fieldName.substring(0, 1).toUpperCase()
               + fieldName.substring(1);
      }
   }

   private static String msg(String key) {
      return PropertyUtil.getProperty(key);
   }
}

------ For reference only ---------------------------- -----------

/**
 * The UserInfoBean class contains all the user info.
 */
public class UserInfoBean implements EntityBean {
   private String username;

   private String password;

   private String role;

   private String type;

   private String regTime;

   private Map<String, Object> dynamicInfo;

   public UserInfoBean() {
      dynamicInfo = new LinkedHashMap<String, Object>();
   }

   /**
    * @return the password
    */
   public String getPassword() {
      return password;
   }

   /**
    * @param password the password to set
    */
   public void setPassword(String password) {
      this.password = password;
   }

   /**
    * @return the type
    */
   public String getType() {
      return type;
   }

   /**
    * @param type the type to set
    */
   public void setType(String type) {
      this.type = type;
   }

   /**
    * @return the regTime
    */
   public String getRegTime() {
      return regTime;
   }

   /**
    * @param regTime the regTime to set
    */
   public void setRegTime(String regTime) {
      this.regTime = regTime;
   }

   /**
    * @return the role
    */
   public String getRole() {
      return role;
   }

   /**
    * @param role the role to set
    */
   public void setRole(String role) {
      this.role = role;
   }

   /**
    * @return the username
    */
   public String getUsername() {
      return username;
   }

   /**
    * @param username the username to set
    */
   public void setUsername(String username) {
      this.username = username;
   }

   public String getClsName() {
      return getClass().getName();
   }

   public String getClsSimpleName() {
      return getClass().getSimpleName();
   }

   public String getSheetName() {
      return "userinfo";
   }

   public String getTableName() {
      return "USER_INFO";
   }

   public void putDynamicInfo(String title, Object value) {
      dynamicInfo.put(title, value);
   }

   public Map<String, Object> getDynamicInfo() {
      return dynamicInfo;
   }

   public String toString() {
      StringBuffer string = new StringBuffer();
      string.append("username = " + getUsername());
      string.append(", password = " + getPassword());
      string.append(", role = " + getRole());
      string.append(", purview = " + getType());
      string.append(", regTime = " + getRegTime());

      return string.toString();
   }
}

------ For reference only --------------------- ------------------
Thank you

UserInfoBean_ch.properties
# excel title to UserInfoBean property
UserInfoBean_ username = username
UserInfoBean_ password = password
UserInfoBean_ role = role
UserInfoBean_ permission = purview
UserInfoBean_ Registration Date = regTime

# UserInfoBean property to excel title
UserInfoBean_username = username
UserInfoBean_password = password
UserInfoBean_role = Role
UserInfoBean_purview = Permissions
UserInfoBean_regTime = Registration Date

UserInfoBean.properties

# excel title to UserInfoBean property
UserInfoBean_ \ u7528 \ u6237 \ u540d = username
UserInfoBean_ \ u5bc6 \ u7801 = password
UserInfoBean_ \ u89d2 \ u8272 = role
UserInfoBean_ \ u6743 \ u9650 = purview
UserInfoBean_ \ u6ce8 \ u518c \ u65e5 \ u671f = regTime

# UserInfoBean property to excel title
UserInfoBean_username = \ u7528 \ u6237 \ u540d
UserInfoBean_password = \ u5bc6 \ u7801
UserInfoBean_role = \ u89d2 \ u8272
UserInfoBean_purview = \ u6743 \ u9650
UserInfoBean_regTime = \ u6ce8 \ u518c \ u65e5 \ u671f

userinfo.xls Username Password roles

admin admin123 admin
test test other

------ For reference only ---------------------------------- -----

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

public class ExcelDemo {
   
   /**
    * @param args
    */
   public static void main(String[] args) {
      try {
         UserInfoBean userBean = new UserInfoBean();
         String fileName = "userinfo.xls";
         String path = ExcelDemo.class.getResource(fileName).getFile();
         File file = new File(path);
         SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
         List<BaseBean> userList = ExcelEditor.readExcel(file, 
               new EntityBean[] {userBean}, null).get(userBean);
         for(int i = 0; i < userList.size(); i++) {
            System.err.println(userList.get(i));
            if(userList.get(i) instanceof TitleBean) {
               ((TitleBean) userList.get(i)).put("regTime");
            }

            if(userList.get(i) instanceof UserInfoBean) {
               ((UserInfoBean) userList.get(i)).setRegTime(sdf.format(new Date()));
            }
         }

         path = path.replace(fileName, "userinfo2.xls");
         System.err.println(path);
         FileOutputStream out = new FileOutputStream(new File(path));
         ExcelEditor.writeExcel(out, userList);
         out.flush();
         out.close();
      }
      catch(Exception e) {
         e.printStackTrace();
      }
   }
}


finished, thank you. This is a read-write Excel examples , we hope to help.
------ For reference only -------------------------------------- -
an Excel Sheet corresponds to a EntityBean implementation class , in this case to UserInfoBean for example , Excel Sheet associate with the header files and UserInfoBean resource properties . If the header contains a dynamic and can be accessed by dynamicInfo .
------ For reference only -------------------------------------- -
this thing covered up Hey
------ For reference only ------------------------.!! ---------------
involved jar:
poi-3.6.jar
poi-3.6-dom4j-1.6.1.jar
poi-3.6-geronimo-stax-api_1.0_spec-1.0.jar
poi-3.6-xmlbeans-2.3.0.jar
poi-3.6-ooxml-20091214.jar
poi-3.6-ooxml-schemas-20091214.jar
------ For reference only ----------------------- ----------------
to myself haha did not get off the
------ For reference only ---------------------------------------
company code to take it out back Posts can only return a certain length , finishing back under the package .
------ For reference only -------------------------------------- -


Here was a business need , write clearly , you can put together .
Source Download http://download.csdn.net/source/3561738
----- - For reference only ---------------------------------------
Thanks for sharing , top a
------ For reference only ------------------------------------- -
to force download credit
------ For reference only -------------------------- -------------
xuexi ...
------ For reference only ------------------ ---------------------
use ing
------ For reference only ----------- ----------------------------
with poi really more ah ! Learn about, oh thank you for sharing !
------ For reference only -------------------------------------- -
cattle, used POI done an Excel export procedures. Learn.
------ For reference only -------------------------------------- -
mark ~ ~
------ For reference only ------------------------------- --------
good thing, if you can download package just fine !
------ For reference only -------------------------------------- -
learning under the
------ For reference only ------------------------------- --------
good things , top up .
------ For reference only -------------------------------------- -
good Dingxi , roof ......
------ For reference only ----------------------- ----------------












go after no download source address , give examples can be up and running , I mainly want to see the merged cell (cell length how to control the height of the merger ) , insert the check box. Can also send me mail 505777612@qq.com, thank you to my http://topic.csdn.net/u/20110914/10/4506cde6-3421-4082-8ce4-83e2b63e3c47.html





------ For reference only ---------------------------------- -----
today jxl just learn something poi and thank LZ a
------ For reference only ----------- ----------------------------
landlord did not know the code to explain the bearded grandfather's 'd understand the
------ For reference only ------------------------------------- -
landlord can not share your bag down ! ! bp_2011@163.com
------ For reference only --------------------------------- ------
http://topic.csdn.net/u/20110929/18/07e67358-776b-494b-a2ad-9e09bb60efcf.html?seed=844493765&r=75798780 # r_75798780
landlord to help me down , thank you. . .
------ For reference only -------------------------------------- -
http://topic.csdn.net/u/20110929/18/07e67358-776b-494b-a2ad-9e09bb60efcf.html?seed=844493765&r=75798780 # r_75798780
--- --- For reference only ---------------------------------------
http://www.iteye.com/topic/1116095 landlord to help look . . .
------ For reference only -------------------------------------- -
very good , up, top
------ For reference only ---------------------------- -----------
good good good
------ For reference only --------------------- ------------------
LZ import Excel2007 brother wrote it? Recent optimization framework originally struts1.2 now need support excel2007, problems occur when the file stream references , a problem that comes between the struts like the InputStream and XssfWorkBook need to upload into the stream interface , do not know if there LZ encountered , thank you.
------ For reference only -------------------------------------- -
LZ can help us to see it? Thank you ~
http://topic.csdn.net/u/20111209/14/c7aa650e-bb7c-4fe0-bb1d-a5eff38523ce.html
------ For reference only ------- --------------------------------
cyclomatic complexity too !
------ For reference only -------------------------------------- -
lz powerful ah
------ For reference only ------------------------------ ---------
not see the text of a note , the tragedy !
------ For reference only -------------------------------------- -
amount , if everyone has shared so patiently and detailed enough 3q lz
------ For reference only ------ ---------------------------------
very good stuff , download it to learn , thank LZ Share
------ For reference only -------------------------------------- -
  The reply was deleted at the moderator 2012-05-08 17:09:38

------ For reference only ---------------------------------- -----
thanks so much , recently busy with this , sort of a bit dizzy
------ For reference only ---------------- -----------------------
class ExcelEditor method readExcel

InputStream in = new FileInputStream (excel);
Workbook book = null;

try {
book = new HSSFWorkbook (in); } catch (OutOfMemoryError e) {
String msg = "The file" + excel.getName ()
+ "data is error, please delete invalid data!";

throw new Exception (msg);
} catch (OfficeXmlFileException e) {
in = new FileInputStream (excel);
book = new XSSFWorkbook (in);
}


error Type mismatch: cannot convert from HSSFWorkbook to Workbook is how it happened ? How to modify it?
------ For reference only -------------------------------------- -


If the book = new HSSFWorkbook (in); to book = (Workbook) new HSSFWorkbook (in);
and error org.apache.poi.hssf.usermodel.HSSFWorkbook cannot be cast to org.apache.poi.ss.usermodel.Workbook
------ For reference only ---------------------------------------


package references will not be wrong to see HSSFWorkbook parent Workbook package name .
------ For reference only -------------------------------------- -


This deal just fine idea Kazakhstan
------ For reference only -------------------------- -------------
do business systems, export excel is very common . Thank you for sharing . . .
------ For reference only -------------------------------------- -
If you want to export one million rows of data , the virtual machine will not dry Sia ...
------ For reference only ----------? -----------------------------
very powerful ~ ~ ~
------ For reference only ---------------------------------------
very good ! Write down the spare
------ For reference only ----------------------------------- ----
landlord package upload it.
------ For reference only -------------------------------------- -
there is no servlet example , first read, and then add form data obtained from the jsp to read the excel table , followed in turn will get added to the list after the next line , did not get one data is added to the same table , it will not cover the kind of data , LZ do not know if I have this example ;

没有评论:

发表评论