javaで実現したエクスポートExcelツール類の例

15312 ワード

本論文の例は、Java実装の導出Excelツールクラスを述べている。皆さんに参考にしてあげます。具体的には以下の通りです。
Excel ExportUtil:

package com.excel;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.Number;
import jxl.write.NumberFormat;
import jxl.write.WritableCellFormat;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;
/**
 *   excel  
 * 
 * @author
 * 
 */
public class ExcelExportUtil {
  /**
   *    
   * 
   */
  public ExcelExportUtil() {
  }
  /**
   *         excel
   * 
   * @param sheetName
   *      sheet  ,   sheet1
   * @param nf
   *               :jxl.write.NumberFormat nf = new
   *      jxl.write.NumberFormat("#.##");     
   * @param content
   *          ,   excel     
   * @param    
   *               0,1,0,2  : (0,1) (0,2)  ---> 1    、      
   * @param os
   *      excel   
   * @param row
   *              ,    。         
   * @param col
   *              ,    。         
   */
  public void export(String sheetName, NumberFormat nf, String[][] content,
      String[] mergeInfo, OutputStream os, String row, String col) {
    if (VerifyUtil.isNullObject(content, os) || VerifyUtil.isNull2DArray(content)) {
      return;
    }
    //     
    if (VerifyUtil.isNullObject(sheetName)) {
      sheetName = "sheet1";
    }
    Set<Integer> rows = this.getInfo(row);
    Set<Integer> cols = this.getInfo(col);
    WritableWorkbook workbook = null;
    try {
      workbook = Workbook.createWorkbook(os);
      WritableSheet sheet = workbook.createSheet(sheetName, 0);
      for (int i = 0; i < content.length; i++) {
        for (int j = 0; j < content[i].length; j++) {
          if (content[i][j] == null) {
            content[i][j] = "";
          }
          if (isNumber(content[i][j]) && !rows.contains(i)
              && !cols.contains(j)) {//     
            Number number = null;
            if (VerifyUtil.isNullObject(nf)) {//      
              number = new Number(j, i,
                  Double.valueOf(content[i][j]));
            } else {//      ,     
              jxl.write.WritableCellFormat wcfn = new jxl.write.WritableCellFormat(
                  nf);
              number = new Number(j, i,
                  Double.valueOf(content[i][j]), wcfn);
            }
            sheet.addCell(number);
          } else {//      
            WritableCellFormat format = new WritableCellFormat();
            if (rows.contains(i) || cols.contains(j)) {
              format.setAlignment(jxl.format.Alignment.CENTRE);
            } else {
              format.setAlignment(jxl.format.Alignment.LEFT);
            }
            format.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);
            Label label = new Label(j, i, content[i][j], format);
            sheet.addCell(label);
          }
        }
      }
      this.merge(sheet, mergeInfo);
      workbook.write();
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      try {
        workbook.close();
        os.close();
      } catch (WriteException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
  }
  /**
   *        excel,      ,    ,    
   * 
   * @param sheetName
   *      sheet  ,   sheet1
   * @param content
   *          ,   excel     
   * @param os
   *      excel   
   */
  public void exportFormatExcel(String[][] content, String sheetName,
      OutputStream os) {
    if (VerifyUtil.isNullObject(content, os) || VerifyUtil.isNull2DArray(content)) {
      return;
    }
    //     
    if (VerifyUtil.isNullObject(sheetName)) {
      sheetName = "sheet1";
    }
    WritableWorkbook workbook = null;
    try {
      workbook = Workbook.createWorkbook(os);
      WritableSheet sheet = workbook.createSheet(sheetName, 0);
      for (int i = 0; i < content.length; i++) {
        for (int j = 0; j < content[i].length; j++) {
          if (content[i][j] == null) {
            content[i][j] = "";
          }
          WritableCellFormat format = new WritableCellFormat();
          format.setAlignment(jxl.format.Alignment.LEFT);
          format.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);
          Label label = new Label(j, i, content[i][j], format);
          sheet.addCell(label);
        }
      }
      workbook.write();
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      try {
        workbook.close();
      } catch (WriteException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
  }
  /**
   *        excel,      ,    ,    
   * 
   * @param sheetName
   *      sheet  ,   sheet1
   * @param content
   *      Map,   excel     
   * @param os
   *      excel   
   */
  public void exportFormatExcel(Map<String, String[][]> content,
      String[] salary_name_array, String sheetName, OutputStream os)
       {
    if (VerifyUtil.isNullObject(content, os) || content.size() == 0) {
      return;
    }
    //     
    if (VerifyUtil.isNullObject(sheetName)) {
      sheetName = "sheet1";
    }
    WritableWorkbook workbook = null;
    try {
      workbook = Workbook.createWorkbook(os);
      WritableSheet sheet = workbook.createSheet(sheetName, 0);
      int index = 0;
      for (int k = 0; k < salary_name_array.length; k++) {
        String[][] value = (String[][]) content
            .get(salary_name_array[k]);
        if (value != null && value.length > 0) {
          if (index != 0) {
            index++;
          }
          WritableCellFormat format1 = new WritableCellFormat();
          format1.setAlignment(jxl.format.Alignment.LEFT);
          format1.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);
          Label label1 = new Label(0, index, salary_name_array[k],
              format1);
          sheet.addCell(label1);
          for (int i = 0; i < value.length; i++) {
            index++;
            for (int j = 0; j < value[i].length; j++) {
              if (value[i][j] == null) {
                value[i][j] = "";
              }
              WritableCellFormat format = new WritableCellFormat();
              format.setAlignment(jxl.format.Alignment.LEFT);
              format.setVerticalAlignment(jxl.format.VerticalAlignment.CENTRE);
              Label label = new Label(j, index, value[i][j],
                  format);
              sheet.addCell(label);
            }
          }
        }
      }
      workbook.write();
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      try {
        workbook.close();
      } catch (WriteException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
    }
  }
  /**
   *     
   * @param sheet
   *         
   * @param mergeInfo
   *               
   * @throws RowsExceededException
   * @throws NumberFormatException
   * @throws WriteException
   */
  private void merge(WritableSheet sheet, String[] mergeInfo)
      throws RowsExceededException, NumberFormatException, WriteException {
    if (VerifyUtil.isNullObject(sheet) || VerifyUtil.isNull1DArray(mergeInfo)) {
      return;
    } else if (!this.isMergeInfo(mergeInfo)) {
      return;
    } else {
      for (String str : mergeInfo) {
        String[] temp = str.split(",");
        sheet.mergeCells(Integer.parseInt(temp[1]),
            Integer.parseInt(temp[0]), Integer.parseInt(temp[3]),
            Integer.parseInt(temp[2]));
      }
    }
  }
  /**
   *             
   * 
   * @param indexes
   *           
   * @return             
   */
  private Set<Integer> getInfo(String indexes) {
    Set<Integer> set = new HashSet<Integer>();
    if (VerifyUtil.isNullObject(indexes)) {
      return set;
    }
    String[] temp = indexes.split(",", 0);
    for (String str : temp) {
      if (isNumeric(str)) {
        set.add(Integer.parseInt(str));
      }
    }
    return set;
  }
  /**
   *              
   * 
   * @param str
   *          
   * @return true ,false 
   */
  private boolean isNumeric(String str) {
    if (VerifyUtil.isNullObject(str)) {
      return false;
    }
    Pattern pattern = Pattern.compile("[0-9]*");
    return pattern.matcher(str).matches();
  }
  /**
   *           
   * 
   * @param str
   *          
   * @return true ,false 
   */
  private boolean isNumber(String number) {
    //     
    if (VerifyUtil.isNullObject(number)) {
      return false;
    }
    //         
    int index = number.indexOf(".");
    if (index < 0) {
      return isNumeric(number);
    } else {
      //      ".",     
      if (number.indexOf(".") != number.lastIndexOf(".")) {
        return false;
      }
      String num1 = number.substring(0, index);
      String num2 = number.substring(index + 1);
      return isNumeric(num1) && isNumeric(num2);
    }
  }
  /**
   *            
   * 
   * @param mergeInfo
   *                   0,1,0,2  (0,1) (0,2)  
   * @return true  ,false  
   */
  private boolean isMergeInfo(String[] mergeInfo) {
    if (VerifyUtil.isNull1DArray(mergeInfo)) {
      return false;
    } else {
      for (String str : mergeInfo) {
        String[] temp = str.split(",");
        if (VerifyUtil.isNull1DArray(temp) || temp.length != 4) {
          return false;
        } else {
          for (String s : temp) {
            if (!isNumeric(s)) {
              return false;
            }
          }
        }
      }
    }
    return true;
  }
  public static void main(String[] args) {
    ExcelExportUtil ee = new ExcelExportUtil();
    String[][] content = new String[][] { { "", "   ", null, "   " },
        { "   ", "aa", "2.00", "22" }, { "   ", "bb", "3.01", "32" },
        { "   ", "cc", "4.00", "41" } };
    try {
      OutputStream os = new FileOutputStream("D:/test2.xls");
      // ee.export(null,null, content,null, os);
      ee.export(null, null, content,
          new String[] { "0,1,0,2", "1,0,3,0" }, os, "0,1", "0");
    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
}

VeriftyUtil:

package com.excel;
import java.io.OutputStream;
import java.util.Map;
import jxl.write.NumberFormat;
import jxl.write.WritableSheet;
public class VerifyUtil {
  public static boolean isNullObject(String[][] content, OutputStream os) {
    // TODO Auto-generated method stub
    if(content != null && content.length > 0 && os != null)
    {
      return false;
    }
    return true;
  }
  public static boolean isNull2DArray(String[][] content) {
    // TODO Auto-generated method stub
    if(content != null && content.length > 0)
    {
      return false;
    }
    return true;
  }
  public static boolean isNullObject(NumberFormat nf) {
    // TODO Auto-generated method stub
    if(nf != null)
    {
      return false;
    }
    return true;
  }
  public static boolean isNullObject(String sheetName) {
    if(sheetName != null && !"".equals(sheetName.trim()))
    {
      return false;
    }
    return true;
  }
  public static boolean isNullObject(Map<String, String[][]> content,
      OutputStream os) {
    // TODO Auto-generated method stub
    if(content != null && content.size() > 0 && os != null)
    {
      return false;
    }
    return true;
  }
  public static boolean isNull1DArray(String[] mergeInfo) {
    // TODO Auto-generated method stub
    if(mergeInfo != null && mergeInfo.length > 0)
    {
      return false;
    }
    return true;
  }
  public static boolean isNullObject(WritableSheet sheet) {
    // TODO Auto-generated method stub
    if(sheet != null)
    {
      return false;
    }
    return true;
  }
}

java関連の内容についてもっと興味がある読者は、当駅のテーマを調べてもいいです。「Java操作Excel技巧まとめ」、「Java+MySQLデータベースプログラム設計のまとめ」、「Javaデータ構造とアルゴリズム教程」、「Javaファイルとディレクトリの操作テクニックのまとめ」および「Java操作DOMノード技術のまとめ
本論文で述べたように、皆さんのjavaプログラムの設計に役に立ちます。