jxl操作excel読み取り、エクスポートデータベースの導入


jxlフレームは軽くて実用的で、操作excelの問題を解決する良い案です。エクセルを操作するユーティリティクラスとその例を紹介します。
 
 ツールクラス:
package ash_ljv2.framework.util;

import java.io.*;
import java.util.Date;
import java.util.UUID;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.format.UnderlineStyle;
import jxl.read.biff.BiffException;
import jxl.write.*;
import jxl.write.Number;
import jxl.write.Boolean;

public class Excel{
	//    
	private String path;
	private String tableName ;
	private String[] tableCols;
	
	//     
	private Workbook workbook;
	
	public Excel(String path,String tableName,String[] tableCols) throws BiffException,IOException{
		this.tableName = tableName;
		this.tableCols = tableCols;
		this.setPath(path);	
		this.setWorkbook(Workbook.getWorkbook(new java.io.File(path)));
	}
	
	/**
	 *        
	 * @return      
	 */
	public int getNumberOfSheets(Workbook book){
		return book == null ? 0 :book.getNumberOfSheets();
	}
	
	/**
	 *         
	 * @param sheet    
	 * @return       
	 */
	public int getRows(Sheet sheet){
		return sheet == null ?  0 : sheet.getRows();
	}
	
	/**
	 *       
	 * @param sheet    
	 * @return        
	 */
	public int getColumns(Sheet sheet){
		return sheet == null ?  0 : sheet.getColumns();
	}
	
	/**
	 *          
	 * @param sheet    
	 * @param row   
	 * @return        
	 */
	public Cell[] getRows(Sheet sheet,int row){
		return sheet == null || sheet.getRows() < row ? null : sheet.getRow(row);
	}
	
	/**
	 *          
	 * @param sheet    
	 * @param endrow    
	 * @param endCol    
	 * @return        
	 */
	public Cell[][] getCells(Sheet sheet,int endrow,int endcol){
		return getCells(sheet,0,endrow,0,endcol);
	}
	
	/**
	 *          
	 * @param sheet    
	 * @param startrow   
	 * @param endrow    
	 * @param startcol    
	 * @param endCol    
	 * @return        
	 */
	public Cell[][] getCells(Sheet sheet,int startrow,int endrow,int startcol,int endcol)	{
		Cell[][] cellArray = new Cell[endrow-startrow][endcol-startcol];
		int maxRow = this.getRows(sheet);
		int maxCos = this.getColumns(sheet);
		for(int i = startrow ;i < endrow && i < maxRow ; i++){	
		
			for(int j = startcol ; j < endcol && j < maxCos ; j++ ){
			
				cellArray[i-startrow][j-startcol] = sheet.getCell(j, i);
			}
			
		}		
		return cellArray;
	}
	
	/**
	 *      
	 * @param sheet
	 * @param col
	 * @param startrow
	 * @param endrow
	 * @return
	 */
	public Cell[] getColCells(Sheet sheet,int col,int startrow,int endrow){
		Cell[] cellArray = new Cell[endrow-startrow];
		int maxRow = this.getRows(sheet);
		int maxCos = this.getColumns(sheet);
		if(col <= 0 || col > maxCos || startrow > maxRow || endrow < startrow){
			return null;
		}
		if(startrow < 0){
			startrow = 0;
		}
		for(int i = startrow ;i < endrow && i < maxRow ; i++){
			cellArray[i-startrow] = sheet.getCell(col,i);
		}
		return cellArray;
	}
	
	/**
	 *      
	 * @param sheet
	 * @param row
	 * @param startcol
	 * @param endcol
	 * @return
	 */
	public Cell[] getRowCells(Sheet sheet,int row,int startcol,int endcol){
		Cell[] cellArray = new Cell[endcol-startcol];
		int maxRow = this.getRows(sheet);
		int maxCos = this.getColumns(sheet);
		if(row <= 0 || row > maxRow || startcol > maxCos || endcol < startcol){
			return null;
		}
		if(startcol < 0){
			startcol = 0;
		}
		for(int i = startcol ;i < startcol && i < maxCos ; i++){
			cellArray[i-startcol] = sheet.getCell(i,row);
		}
		return cellArray;
	}
		
	/**
	 *     ID
	 * @return
	 */
	public static String getStrRandomId(){
		String uuid = UUID.randomUUID().toString().replace("-","");   
		return uuid; 
	}
	
	/**
	 *   SQL  (                )
	 * @param sheet    
	 * @param startrow    
	 * @param endrow    
	 * @param startcol    
	 * @param endcol    
	 * @return SQL    
	 */
	public Object[] constrctCellsSql(Sheet sheet,int startrow,int endrow,int startcol,int endcol,String payTime){
		Cell[][] cellArray = getCells(sheet, startrow, endrow,startcol,endcol);
		java.util.ArrayList<String> list = new java.util.ArrayList<String>();
		StringBuffer bf = new StringBuffer("INSERT INTO " + tableName+"(ID,");
		for(int i = 0 ; tableCols != null &&  i < tableCols.length ; i++){
			if(i != tableCols.length -1)
				bf.append(tableCols[i]).append(",");
			else
				bf.append(tableCols[i]).append("");
			
		}
		bf.append(",PAY_TIME) VALUES ");
		for(int i = 0;i< cellArray.length;i++){	
			//           
			StringBuffer sqlBuffer = new StringBuffer();	
			sqlBuffer.append(bf.toString()+"('"+getStrRandomId()+"',");	
			Cell[] cell = cellArray[i];
			if(tableCols != null && cell != null &&  tableCols.length != cell.length)
				continue;
			for(int j = 0 ; j < cell.length; j++){
				String tmp = "";
				if(cell[j] != null && cell[j].getContents() != null){
					tmp = (String)cell[j].getContents();
				}
				if(j != cell.length -1 )
					sqlBuffer.append("'").append(tmp).append("',");
				else
					sqlBuffer.append("'").append(tmp).append("'");				
			}
			//      
			sqlBuffer.append(",").append("to_date('"+payTime+"','YYYY-MM-DD HH24:MI:SS')");
			sqlBuffer.append(")");
			list.add(sqlBuffer.toString());	
			System.out.println(sqlBuffer.toString());
		}
		System.out.println(list);
		return list.toArray();
	}
	

	/**
	 *   Excel    
	 * @return Excel    
	 */
	public String getPath(){
		return this.path;
	}
	
	/**
	 *   Excel    
	 * @param path Excel    
	 */
	public void setPath(String path){
		this.path = path;
	}
	/**
	 *        
	 */
	public Workbook getWorkbook(){
		return this.workbook;
	}
	
	/**
	 *        
	 * @param workbook      
	 */
	public void setWorkbook(Workbook workbook){
		this.workbook = workbook;
	}
	
	/**
	 * 
	 * @param args
	 */
	public static void main(String[] args){
		try {
			File fileWrite = new File("c:/testWrite.xls");
        			fileWrite.createNewFile();
	       		OutputStream os = new FileOutputStream(fileWrite);
	       		Excel.writeExcel(os);
       		} catch (IOException e) {
        			// TODO Auto-generated catch block
 			e.printStackTrace();
 		}
	}
}
 
クラスを読み込み:
package cn.doc.service.impl;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletContext;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;

import com.opensymphony.xwork2.ActionContext;

import pojo.TblTableTemplate;
import ash_ljv2.framework.util.Excel;
import ash_ljv2.framework.util.PageBean;
import cn.doc.dao.TableTemplateDao;
import cn.doc.service.TableTemplateService;

public class TableTemplateServiceImpl implements TableTemplateService{
	private TableTemplateDao tableTemplateDao; 

	public TableTemplateDao getTableTemplateDao() {
		return tableTemplateDao;
	}

	public void setTableTemplateDao(TableTemplateDao tableTemplateDao) {
		this.tableTemplateDao = tableTemplateDao;
	}
	
	/**
	 *   excel
	 * @return
	 */
	public List importTableTemplate(String path){
		ArrayList list=new ArrayList();
		ServletContext request = (ServletContext) ActionContext.getContext()
		.get("com.opensymphony.xwork2.dispatcher.ServletContext");
		try {
			Excel excel = new Excel(request.getRealPath(path),null,null);
			Workbook workbook = excel.getWorkbook();
			Sheet sheet = workbook.getSheet(0);
			int a = excel.getRows(sheet);      //    
			int m=excel.getColumns(sheet);  //    
			Cell[][] c = excel.getCells(sheet,0,a,0,m);
			String f1 = null,f3=null;
			for(int i =0 ; i < c.length;i++){
				Cell[] obj = c[i];
				for(int j =0 ;j< obj.length; j++ ){
					 f1=obj[j].getContents().toString();
					list.add(f1);
				}
			}	
		} catch (Exception e) {
			e.printStackTrace();
		}
		return list;
	}
} 

 
データベースクラスをインポート:
Excel excel=null;
Workbook workbook=null;
Connection conn = session.connection();
ServletContext request = (ServletContext) ActionContext.getContext().get("com.opensymphony.xwork2.dispatcher.ServletContext");
try {
	excel = new Excel(request.getRealPath(path),"tbl_name",new String[]{"NAME","TYPE"}); //       
}catch(Exception e) {
	//e.printStackTrace();					
}
workbook = excel.getWorkbook();
Sheet sheet = workbook.getSheet(0);
Object[] obj=excel.constrctCellsSql(sheet,1,excel.getRows(sheet),0,excel.getColumns(sheet),payTime);  //payTime           
//          ......				
for(int i=0;i<obj.length;i++){
	Statement stmt;
	try {
		stmt = conn.createStatement();
		stmt.execute(obj[i].toString());
		stmt.close();
	} catch (SQLException e) {
		throw new AppException("            !");
	}
}

  
 ここではエクセルをエクスポートしません。エクセルの属性を設定します。データはどの行のどの列に位置していますか?jxlはexcelの属性に対して少し弱くて、フォーマットの美観などの複雑な機能を制御するならば、poiを使うことを提案します。