2012-06-12 19 views
0

我使用apache poi從excel讀取數據到mysql表。我曾爲2個領域的Excel表單做過。我的代碼是這樣的,將變量列excel表導入到mysql中使用java

try 
     { 
      fis = new FileInputStream(filePath); 


     //creating workbook, sheet(from poi jar file) 
     HSSFWorkbook workBook = new HSSFWorkbook(fis); 
     HSSFSheet sheet = workBook.getSheetAt(0); 
     //Iterator for iterating rows in sheet 
     Iterator itr = sheet.iterator(); 
     while(itr.hasNext()) 
     { 

      HSSFRow row = (HSSFRow) itr.next(); 
      Iterator cell = row.cellIterator(); 
      List data = new ArrayList(); 
      while(cell.hasNext()) 
      { 
       HSSFCell value = (HSSFCell) cell.next();      
       if (value.getCellType() == Cell.CELL_TYPE_NUMERIC) 
       { 
        data.add(value.getNumericCellValue()); 
       } 
       else if (value.getCellType() == Cell.CELL_TYPE_BOOLEAN) 
       { 
        data.add(value.getBooleanCellValue()); 
       } 
       else if (value.getCellType() == Cell.CELL_TYPE_STRING) 
       { 
        data.add(value.getStringCellValue()); 
       } 
      } 
      sheetData.add(data); 

     } 
    } 
    catch (Exception e) { 
     // TODO: handle exception 
    } 

然後把數據放在一個數組列表中。十插入到數據庫..但 現在我需要該系統獲得具有變化數量cloumns的excel文件。我可以實現它嗎?我只是需要一些幫助。所以PLZ幫助我一些想法和可能的一些代碼。

在此先感謝。 sujith

+0

這些excel文件是否完全未被您的應用程序所知,或者,您的應用程序是否在某處存儲了某些excel的列信息? –

+0

我的應用程序將數據放到15列的表格中。但是我的excel表格列可能會在2-15之間變化 –

回答

0

當迭代單行

if (value.getCellType() == Cell.CELL_TYPE_NUMERIC){ 
        data.add(value.getNumericCellValue());     
} 

您可以添加一個新的,如果塊,檢查

if(value.getCellType() == Cell.CELL_TYPE_BLANK){ 
break; 
} 

我在這裏假設你的列中的所有數據將被同步( 1 2 3 4空白)而不是這樣(1空白空白2 3 4 5)。所以,當你獲得空白類型的時候,你的迭代器將轉移到下一行。

希望這會有所幫助。

0

您可以使用excel表的第一行來存儲mysql表的列名,所以您將有一個列索引 - 列名映射信息。

然後,當插入到mysql表中時,可以選擇第一行中的列名進行操作。例如

Excel中1

========================= 
    | A  | B  | C 
===+========+========+====== 
1 | name | gender | age <-- column name row 
---+--------+--------+------ 
2 | josh | male | 28 
---+--------+--------+------ 
3 | linda | female | 22 
---------------------------- 

SQL 1

INSERT INTO table (name, gender, age) VALUES ('josh', 'male', 28),('linda', 'female', 22) 

的Excel 2

================== 
    | A  | B 
===+========+======== 
1 | name | country <-- column name row 
---+--------+-------- 
2 | 張三 | China 
---+--------+-------- 
3 | emily | USA 
--------------------- 

SQL 2

INSERT INTO table (name, country) VALUES ('張三', 'China'),('emily', 'USA') 
0

我們還可以用簡單的最佳捷徑2上傳Excel表導入數據庫

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> 
<title>Insert title here</title> 
</head> 
<body> 
<form action="./ExcelSample" method="post" id="formdata" 
    enctype="multipart/form-data" onsubmit="return excelUpload('Conform')"> 
<label for="inputSuccess2" class="control-label"> 
<div id="scn">Select Excel File</div> 
</label> <input type="file" name="excel" id="excelfile" 
    class="form-control active"> <label class="control-label">&nbsp;</label> 
<input type="submit" class="form-control btn btn-orange" id="Upload" 
    value="Upload"></form> 
</body> 
</html> 

package com.excel.Sample.ExcelAnn; 

import java.lang.annotation.ElementType; 
import java.lang.annotation.Retention; 
import java.lang.annotation.RetentionPolicy; 
import java.lang.annotation.Target; 

@Retention(RetentionPolicy.RUNTIME) 
@Target(value=ElementType.METHOD) 
public @interface ExcelColumn { 
    boolean ignore() default false; 
    String label() default ""; 
} 

package com.excel.Sample.ExcelAnn; 

import java.lang.annotation.ElementType; 
import java.lang.annotation.Retention; 
import java.lang.annotation.RetentionPolicy; 
import java.lang.annotation.Target; 

@Retention(RetentionPolicy.RUNTIME) 
@Target(value=ElementType.TYPE) 
public @interface ExcelReport { 
    String reportName(); 
} 


    package com.excel.Sample.Actions; 

import java.io.FileNotFoundException; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.io.InputStream; 
import java.lang.reflect.Method; 
import java.util.ArrayList; 
import java.util.Date; 
import java.util.HashMap; 
import java.util.Iterator; 
import java.util.List; 
import java.util.Map; 

import org.apache.poi.hssf.usermodel.HSSFCellStyle; 
import org.apache.poi.hssf.usermodel.HSSFSheet; 
import org.apache.poi.hssf.usermodel.HSSFWorkbook; 
import org.apache.poi.hssf.util.HSSFColor; 
import org.apache.poi.ss.usermodel.Cell; 
import org.apache.poi.ss.usermodel.CellStyle; 
import org.apache.poi.ss.usermodel.Row; 
import org.apache.poi.ss.usermodel.Sheet; 
import org.apache.poi.ss.usermodel.Workbook; 

import com.excel.Sample.ExcelAnn.ExcelColumn; 
import com.excel.Sample.ExcelAnn.ExcelReport; 

public class ExcelAction { 
    private HSSFWorkbook workbook = null; 
    private String workbookName = "Book1.xls"; 
    private Map<String, String> fieldLabelMap = new HashMap<String, String>(); 
    private List<String> orderLabels = new ArrayList<String>(); 
    private CellStyle columnHeaderCellStyle = null; 

    public ExcelAction() { 
     initialize(); 
    } 

    private void initialize() { 
     setWorkbook(new HSSFWorkbook()); 
     setColumnHeaderCellStyle(createColumnHeaderCellStyle()); 
    } 

    private CellStyle createColumnHeaderCellStyle() { 
     CellStyle cellStyle = getWorkbook().createCellStyle(); 
     cellStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); 
     cellStyle.setFillBackgroundColor(new HSSFColor.GREY_25_PERCENT() 
       .getIndex()); 
     cellStyle.setBorderTop(HSSFCellStyle.BORDER_THIN); 
     cellStyle.setBorderLeft(HSSFCellStyle.BORDER_THIN); 
     cellStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN); 
     cellStyle.setBorderRight(HSSFCellStyle.BORDER_THIN); 
     return cellStyle; 
    } 

    public void closeWorksheet() { 
     FileOutputStream fileOut; 
     try { 
      fileOut = new FileOutputStream(getWorkbookName()); 
      getWorkbook().write(fileOut); 
      fileOut.close(); 
     } catch (FileNotFoundException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 

    private HSSFSheet getSheetWithName(String name) { 
     HSSFSheet sheet = workbook.getSheet(name); 
     return sheet; 
    } 

    private void initializeForRead(InputStream inp) throws IOException { 
     workbook = new HSSFWorkbook(inp); 
    } 

    private <T> void processAnnotations(T object) { 
     Class<?> clazz = object.getClass(); 
     ExcelReport reportAnnotation = (ExcelReport) clazz 
       .getAnnotation(ExcelReport.class); 


     for (Method method : clazz.getMethods()) { 

      ExcelColumn excelColumn = method.getAnnotation(ExcelColumn.class); 
      if ((excelColumn != null) && !excelColumn.ignore()) { 
       getFieldLabelMap().put(excelColumn.label(), method.getName()); 
       getOrderLabels().add(excelColumn.label()); 
      } 
     } 
    } 

    @SuppressWarnings("unchecked") 
    public <T> List<T> readData(String classname, InputStream inp) 
      throws Exception { 
     Class clazz = Class.forName(classname); 
     processAnnotations(clazz.newInstance()); 
     initializeForRead(inp); 
     HSSFSheet sheet = getSheetWithName("Sheet1"); 
     List<T> result = new ArrayList<T>(); 
     Map<String, String> mp = new HashMap<String, String>(); 
     Iterator<Row> rowIterator = sheet.rowIterator(); 
     int rowCount = 0; 
     while (rowIterator.hasNext()) { 
      T one = (T) clazz.newInstance(); 
      try { 
       int colCount = 0; 
       result.add(one); 
       Row row = rowIterator.next(); 
       Iterator<Cell> cellIterator = row.cellIterator(); 
       while (cellIterator.hasNext()) { 
        Cell cell = cellIterator.next(); 
        if (rowCount == 0) { 
         mp.put(colCount + "", cell.getStringCellValue() 
           .toString().trim()); 

        } else { 
         int type = cell.getCellType(); 
         String labelName = mp.get(colCount + ""); 
         String getter = getFieldLabelMap().get(labelName); 
         String fieldName = getter.substring(3); 
         fieldName = decapitalize(fieldName); 
         Method method = constructMethod(clazz, fieldName); 
         if (type == 1) { 
          String value = cell.getStringCellValue(); 
          Object[] values = new Object[1]; 
          values[0] = value; 
          method.invoke(one, values); 
         } else if (type == 0) { 
          Double num = cell.getNumericCellValue(); 
          Class<?> returnType = getGetterReturnClass(clazz, 
            fieldName); 
          if (returnType == Integer.class) { 
           method.invoke(one,(Integer) num.intValue()); 
          } else if (returnType == Double.class) { 
           method.invoke(one, (Integer) num.intValue()); 
          } else if (returnType == Float.class) { 
           method.invoke(one, num.floatValue()); 
          } else if (returnType == Date.class) { 
           method.invoke(one, cell.getDateCellValue()); 
          } 
         } else if (type == 3) { 
          double num = cell.getNumericCellValue(); 
          Object[] values = new Object[1]; 
          values[0] = num; 
          method.invoke(one, values); 
         } 
        } 
        colCount++; 
       } 
      } catch (Exception e) { 
       System.out.println(e); 
      } 
      rowCount++; 
     } 
     return result; 
    } 

    private Class<?> getGetterReturnClass(Class<?> clazz, String fieldName) { 
     String methodName = "get" + capitalize(fieldName); 
     Class<?> returnType = null; 
     for (Method method : clazz.getMethods()) { 
      if (method.getName().equals(methodName)) { 
       returnType = method.getReturnType(); 
       break; 
      } 
     } 
     return returnType; 
    } 

    @SuppressWarnings("unchecked") 
    private Method constructMethod(Class clazz, String fieldName) 
      throws SecurityException, NoSuchMethodException { 
     Class<?> fieldClass = getGetterReturnClass(clazz, fieldName); 
     return clazz.getMethod("set" + capitalize(fieldName), fieldClass); 
    } 

    public <T> void writeReportToExcel(List<T> data) throws Exception { 
     processAnnotations(data.get(0)); 
     Sheet sheet = getWorkbook().createSheet(
       data.get(0).getClass().getName()); 
     int rowCount = 0; 
     int columnCount = 0; 
     Row row = sheet.createRow(rowCount++); 
     for (String labelName : getOrderLabels()) { 
      Cell cel = row.createCell(columnCount++); 
      cel.setCellValue(labelName); 
      cel.setCellStyle(getColumnHeaderCellStyle()); 
     } 
     Class<? extends Object> classz = data.get(0).getClass(); 
     for (T t : data) { 
      row = sheet.createRow(rowCount++); 

      columnCount = 0; 

      for (String label : getOrderLabels()) { 
       String methodName = getFieldLabelMap().get(label); 
       Cell cel = row.createCell(columnCount); 
       Method method = classz.getMethod(methodName); 
       Object value = method.invoke(t, (Object[]) null); 
       if (value != null) { 
        if (value instanceof String) { 
         cel.setCellValue((String) value); 
        } else if (value instanceof Long) { 
         cel.setCellValue((Long) value); 
        } else if (value instanceof Integer) { 
         cel.setCellValue((Integer) value); 
        } else if (value instanceof Double) { 
         cel.setCellValue((Double) value); 
        } 
       } 
       columnCount++; 
      } 
     } 
    } 

    public Map<String, String> getFieldLabelMap() { 
     return fieldLabelMap; 
    } 

    public void setFieldLabelMap(Map<String, String> fieldLabelMap) { 
     this.fieldLabelMap = fieldLabelMap; 
    } 

    public List<String> getOrderLabels() { 
     return orderLabels; 
    } 

    public void setOrderLabels(List<String> orderLabels) { 
     this.orderLabels = orderLabels; 
    } 

    public String capitalize(String string) { 
     String capital = string.substring(0, 1).toUpperCase(); 
     return capital + string.substring(1); 
    } 

    public String decapitalize(String string) { 
     String capital = string.substring(0, 1).toLowerCase(); 
     return capital + string.substring(1); 
    } 

    public String getWorkbookName() { 
     return workbookName; 
    } 

    public void setWorkbookName(String workbookName) { 
     this.workbookName = workbookName; 
    } 

    void setWorkbook(HSSFWorkbook workbook) { 
     this.workbook = workbook; 
    } 

    Workbook getWorkbook() { 
     return workbook; 
    } 

    public CellStyle getColumnHeaderCellStyle() { 
     return columnHeaderCellStyle; 
    } 

    public void setColumnHeaderCellStyle(CellStyle columnHeaderCellStyle) { 
     this.columnHeaderCellStyle = columnHeaderCellStyle; 
    } 

} 


package com.excel.Sample.Model; 

import java.util.Date; 

import javax.persistence.Column; 
import javax.persistence.Entity; 
import javax.persistence.GeneratedValue; 
import javax.persistence.Id; 
import javax.persistence.Table; 

import com.excel.Sample.ExcelAnn.ExcelColumn; 

@Entity 
@Table(name = "directory") 
public class Directory { 
    @Id 
    @GeneratedValue 
    @Column(name = "id") 
    private Integer id; 
    @Column(name = "Test_Name") 
    private String name; 
    @Column(name = "Path", nullable = false) 
    private String path; 
    @Column(name = "Directory", nullable = false) 
    private String directory; 
    @Column(name = "ContainedFiles", nullable = false) 
    private Integer containedFiles; 

    @Column(name = "DateFormate", nullable = false) 
    private Date dateFormate; 

    public Integer getId() { 
     return id; 
    } 

    public void setId(Integer id) { 
     this.id = id; 
    } 

    @ExcelColumn(label = "Test Name") 
    public String getName() { 
     return name; 
    } 

    public void setName(String name) { 
     this.name = name; 
    } 

    @ExcelColumn(label = "Path") 
    public String getPath() { 
     return path; 
    } 

    public void setPath(String path) { 
     this.path = path; 
    } 

    @ExcelColumn(label = "Directory") 
    public String getDirectory() { 
     return directory; 
    } 

    public void setDirectory(String directory) { 
     this.directory = directory; 
    } 

    @ExcelColumn(label = "ContainedFiles") 
    public Integer getContainedFiles() { 
     return containedFiles; 
    } 

    public void setContainedFiles(Integer containedFiles) { 
     this.containedFiles = containedFiles; 
    } 

    @ExcelColumn(label = "DateFormate") 
    public Date getDateFormate() { 
     return dateFormate; 
    } 

    public void setDateFormate(Date dateFormate) { 
     this.dateFormate = dateFormate; 
    } 
} 

package com.excel.Sample.Servlet; 

import java.io.IOException; 
import java.io.PrintWriter; 
import java.text.SimpleDateFormat; 
import java.util.List; 

import javax.servlet.ServletException; 
import javax.servlet.http.HttpServlet; 
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse; 

import org.apache.commons.fileupload.FileItem; 
import org.apache.commons.fileupload.FileItemFactory; 
import org.apache.commons.fileupload.FileUploadException; 
import org.apache.commons.fileupload.disk.DiskFileItemFactory; 
import org.apache.commons.fileupload.servlet.ServletFileUpload; 
import org.hibernate.HibernateException; 
import org.hibernate.Session; 
import org.hibernate.Transaction; 

import com.excel.Sample.Actions.ExcelAction; 
import com.excel.Sample.Model.Directory; 
import com.excel.util.HibernateUtil; 

/** 
* Servlet implementation class ExcelSample 
*/ 
public class ExcelSample extends HttpServlet { 
    private static final long serialVersionUID = 1L; 
    public static String modelName = "com.excel.Sample.Model.Directory"; 

    /** 
    * @see HttpServlet#HttpServlet() 
    */ 
    public ExcelSample() { 
     super(); 

     // TODO Auto-generated constructor stub 
    } 

    /** 
    * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse 
    *  response) 
    */ 
    protected void doGet(HttpServletRequest request, 
      HttpServletResponse response) throws ServletException, IOException { 
     // TODO Auto-generated method stub 
    } 

    /** 
    * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse 
    *  response) 
    */ 
    protected void doPost(HttpServletRequest request, 
      HttpServletResponse response) throws ServletException, IOException { 
     // TODO Auto-generated method stub 
     PrintWriter out = response.getWriter(); 
     try { 

      boolean isMultipart = ServletFileUpload.isMultipartContent(request); 
      if (!isMultipart) { 
      } else { 
       FileItemFactory factory = new DiskFileItemFactory(); 
       ServletFileUpload upload = new ServletFileUpload(factory); 
       List items = null; 
       try { 
        items = upload.parseRequest(request); 
       } catch (FileUploadException e) { 
        e.getMessage(); 
       } 
       FileItem item = (FileItem) items.get(0); 
       try { 
        ExcelAction ea = new ExcelAction(); 
        List<Directory> e = ea.readData(modelName, item 
          .getInputStream()); 
        out.println("<table>"); 
        for (int i = 1; i < e.size(); i++) { 
         Directory ex = (Directory) e.get(i); 
         Session session = HibernateUtil.getSessionFactory() 
           .openSession(); 
         Transaction transaction = null; 

         try { 
          transaction = session.beginTransaction(); 
          session.save(ex); 
          transaction.commit(); 
         } catch (HibernateException exp) { 
          transaction.rollback(); 
          exp.printStackTrace(); 
         } finally { 
          session.close(); 
         } 
         String date = new SimpleDateFormat("dd/MM/yyyy") 
           .format(ex.getDateFormate()); 
         out.println("<tr><td>" + ex.getContainedFiles() 
           + " </td><td> " + ex.getDirectory() 
           + " </td><td> " + ex.getPath() + " </td><td> " 
           + ex.getName() + "</td><td> " + date 
           + "</td></tr>"); 
        } 
        out.println("</table>"); 
       } catch (Exception e) { 
        System.out.println(e); 
       } 
      } 
     } catch (Exception e) { 
      System.out.println(e); 
     } 

    } 

} 
  1. Excel的伴侶如下:

測試名稱路徑目錄ContainedFiles DateFormate .settings/home/david/dev/workspaces/De c2009/ExcelAnnotationReport/.settings目錄1 5/2/2013 src/home/david/dev/workspaces/Dec2009/ExcelAnnotationReport/src目錄1 2013/12/3 .classpath1/home/david/dev/workspaces/Dec2009/ExcelAnnotationReport/.classpath1 file1 1 11/4/2013 test/home/david/dev/workspaces/Dec2009/ExcelAnnotationReport/test directory 2013年3月5日 test.xls/home/david/dev/workspaces/Dec2009/ExcelAnnotationReport /測試。xls文件11 6/6/2013 .project /home/david/dev/workspaces/Dec2009/ExcelAnnotationReport/.project file 1 12/7/2013 bin/home/david/dev/workspaces/Dec2009/ExcelAnnotationReport/bin目錄1 6/8/2013

+0

請問您能否詳細說明您的答案,並添加關於您提供的解決方案的更多描述? – abarisone

+0

https://4shared.com/rar/a6NWyhIIba/ExcelFormate.html – Chickenturtle

+0

使用上述鏈接下載上述代碼。如果你看到這個代碼,你可能會清楚的看到代碼。這是基於思考和使用自己的註釋。 – Chickenturtle