程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 更多編程語言 >> 編程解疑 >> 二維數組-String數組之間如何傳值

二維數組-String數組之間如何傳值

編輯:編程解疑
String數組之間如何傳值

package com.excel.action;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
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.poifs.filesystem.POIFSFileSystem;

import jxl.Workbook;
import jxl.format.Alignment;
import jxl.format.Border;
import jxl.format.BorderLineStyle;
import jxl.format.Colour;
import jxl.format.UnderlineStyle;
import jxl.write.Label;
import jxl.write.NumberFormats;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;

public class JxlTable {

private final static JxlTable jxlTable = new JxlTable();

public static JxlTable getInstance() {
    return jxlTable;
}

public JxlTable() {
}

public boolean createTable(String[] body, String filePath) {
    boolean createFlag = true;
    WritableWorkbook book;
    try {
        // 根據路徑生成excel文件
        book = Workbook.createWorkbook(new File(filePath));
        // 創建一個sheet名為"表格"
        WritableSheet sheet = book.createSheet("表格", 0);
        // 設置NO列寬度
        sheet.setColumnView(1, 5);
        // 去掉整個sheet中的網格線
        sheet.getSettings().setShowGridLines(false);
        Label tempLabel = null;

        // 表體輸出
        int bodyLen = body.length;
        // 循環寫入表體內容
        for (int j = 0; j < bodyLen; j++) {
            String[] bodyTempArr = body[j].split(",");
            for (int k = 0; k < bodyTempArr.length; k++) {
                WritableCellFormat tempCellFormat = null;
                tempCellFormat = getBodyCellStyle();
                if (tempCellFormat != null) {
                    if (k == 0 || k == (bodyTempArr.length - 1)) {
                        tempCellFormat.setAlignment(Alignment.CENTRE);
                    }
                }
                tempLabel = new Label(1 + k, 2 + j, bodyTempArr[k],
                        tempCellFormat);
                sheet.addCell(tempLabel);
            }
        }
        book.write();
        book.close();
    } catch (IOException e) {
        createFlag = false;
        System.out.println("EXCEL創建失敗!");
        e.printStackTrace();
    } catch (RowsExceededException e) {
        createFlag = false;
        System.out.println("EXCEL單元設置創建失敗!");
        e.printStackTrace();
    } catch (WriteException e) {
        createFlag = false;
        System.out.println("EXCEL寫入失敗!");
        e.printStackTrace();
    }

    return createFlag;
}

public WritableCellFormat getHeaderCellStyle() {
    WritableFont font = new WritableFont(WritableFont.createFont("宋體"), 10,
            WritableFont.BOLD, false, UnderlineStyle.NO_UNDERLINE);
    WritableCellFormat headerFormat = new WritableCellFormat(
            NumberFormats.TEXT);
    try {
        // 添加字體設置
        headerFormat.setFont(font);
        // 設置單元格背景色:表頭為黃色
        headerFormat.setBackground(Colour.YELLOW);
        // 設置表頭表格邊框樣式
        // 整個表格線為粗線、黑色
        headerFormat.setBorder(Border.ALL, BorderLineStyle.THICK,
                Colour.BLACK);
        // 表頭內容水平居中顯示
        headerFormat.setAlignment(Alignment.CENTRE);
    } catch (WriteException e) {
        System.out.println("表頭單元格樣式設置失敗!");
    }
    return headerFormat;
}

public WritableCellFormat getBodyCellStyle() {
    WritableFont font = new WritableFont(WritableFont.createFont("宋體"), 10,
            WritableFont.NO_BOLD, false, UnderlineStyle.NO_UNDERLINE);
    WritableCellFormat bodyFormat = new WritableCellFormat(font);
    try {
        // 設置單元格背景色:表體為白色
        bodyFormat.setBackground(Colour.WHITE);
        // 設置表頭表格邊框樣式
        // 整個表格線為細線、黑色
        bodyFormat
                .setBorder(Border.ALL, BorderLineStyle.THIN, Colour.BLACK);
    } catch (WriteException e) {
        System.out.println("表體單元格樣式設置失敗!");
    }
    return bodyFormat;
}

   /**
 * 讀取Excel的內容,第一維數組存儲的是一行中格列的值,二維數組存儲的是多少個行
 * @param file 讀取數據的源Excel
 * @param ignoreRows 讀取數據忽略的行數,比喻行頭不需要讀入 忽略的行數為1
 * @return 讀出的Excel中數據的內容
 * @throws FileNotFoundException
 * @throws IOException
 */
public static String[][] getData(File file, int ignoreRows)
       throws FileNotFoundException, IOException {
   List<String[]> result = new ArrayList<String[]>();
   int rowSize = 0;
   BufferedInputStream in = new BufferedInputStream(new FileInputStream(
          file));
   // 打開HSSFWorkbook
   POIFSFileSystem fs = new POIFSFileSystem(in);
   HSSFWorkbook wb = new HSSFWorkbook(fs);
   HSSFCell cell = null;
   for (int sheetIndex = 0; sheetIndex < wb.getNumberOfSheets(); sheetIndex++) {
       HSSFSheet st = wb.getSheetAt(sheetIndex);
       // 第一行為標題,不取
       for (int rowIndex = ignoreRows; rowIndex <= st.getLastRowNum(); rowIndex++) {
          HSSFRow row = st.getRow(rowIndex);
          if (row == null) {
              continue;
          }
          int tempRowSize = row.getLastCellNum() + 1;
          if (tempRowSize > rowSize) {
              rowSize = tempRowSize;
          }
          String[] values = new String[rowSize];
          Arrays.fill(values, "");
          boolean hasValue = false;
          for (short columnIndex = 0; columnIndex <= row.getLastCellNum(); columnIndex++) {
              String value = "";
              cell = row.getCell(columnIndex);
              if (cell != null) {
                 // 注意:一定要設成這個,否則可能會出現亂碼
                 cell.setEncoding(HSSFCell.ENCODING_UTF_16);
                 switch (cell.getCellType()) {
                 case HSSFCell.CELL_TYPE_STRING:
                     value = cell.getStringCellValue();
                     break;
                 case HSSFCell.CELL_TYPE_NUMERIC:
                     if (HSSFDateUtil.isCellDateFormatted(cell)) {
                        Date date = cell.getDateCellValue();
                        if (date != null) {
                            value = new SimpleDateFormat("yyyy-MM-dd")
                                   .format(date);
                        } else {
                            value = "";
                        }
                     } else {
                        value = new DecimalFormat("0").format(cell
                               .getNumericCellValue());
                     }
                     break;
                 case HSSFCell.CELL_TYPE_FORMULA:
                     // 導入時如果為公式生成的數據則無值
                     if (!cell.getStringCellValue().equals("")) {
                        value = cell.getStringCellValue();
                     } else {
                        value = cell.getNumericCellValue() + "";
                     }
                     break;
                 case HSSFCell.CELL_TYPE_BLANK:
                     break;
                 case HSSFCell.CELL_TYPE_ERROR:
                     value = "";
                     break;
                 case HSSFCell.CELL_TYPE_BOOLEAN:
                     value = (cell.getBooleanCellValue() == true ? "Y"
                            : "N");
                     break;
                 default:
                     value = "";
                 }
              }
              if (columnIndex == 0 && value.trim().equals("")) {
                 break;
              }
              values[columnIndex] = rightTrim(value);
              hasValue = true;
          }

          if (hasValue) {
              result.add(values);
          }
       }
   }
   in.close();
   String[][] returnArray = new String[result.size()][rowSize];
   for (int i = 0; i < returnArray.length; i++) {
       returnArray[i] = (String[]) result.get(i);
   }
   return returnArray;
}

/**
 * 去掉字符串右邊的空格
 * @param str 要處理的字符串
 * @return 處理後的字符串
 */
 public static String rightTrim(String str) {
   if (str == null) {
       return "";
   }
   int length = str.length();
   for (int i = length - 1; i >= 0; i--) {
       if (str.charAt(i) != 0x20) {
          break;
       }
       length--;
   }
   return str.substring(0, length);
}



public static void main(String[] args) throws Exception {
     File file = new File("F:/tomcat7/webapps/Excel/upload/3.xls");
       String[][] result = getData(file, 1);
       int rowLength = result.length;
       for(int i=0;i<rowLength;i++) {
           for(int j=0;j<result[i].length;j++) {
              System.out.print(result[i][j]+"\t\t");
           }
           System.out.println();
       }
    String[][] body = result;   //如何傳值?

    String filePath = "F:/tomcat7/webapps/Excel/upload/3333.xls";
    JxlTable testJxl = JxlTable.getInstance();
    boolean flag = testJxl.createTable(body, filePath);  /////在這裡報錯 如何傳值 求助
    if (flag) {
        System.out.println("表格創建成功!!");
    }
}

}

最佳回答:


大概改了下,你試試

package com.excel.action;
 import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;
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.poifs.filesystem.POIFSFileSystem;
import jxl.Workbook;
import jxl.format.Alignment;
import jxl.format.Border;
import jxl.format.BorderLineStyle;
import jxl.format.Colour;
import jxl.format.UnderlineStyle;
import jxl.write.Label;
import jxl.write.NumberFormats;
import jxl.write.WritableCellFormat;
import jxl.write.WritableFont;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;

public class JxlTable {
    private final static JxlTable jxlTable = new JxlTable();
    public boolean createTable(List<String[]>data, String filePath) {
        boolean createFlag = true;
        WritableWorkbook book;
        try {
            // 根據路徑生成excel文件
            book = Workbook.createWorkbook(new File(filePath));
            // 創建一個sheet名為"表格"
            WritableSheet sheet = book.createSheet("表格", 0);
            // 設置NO列寬度
            sheet.setColumnView(1, 5);
            // 去掉整個sheet中的網格線
            sheet.getSettings().setShowGridLines(false);
            Label tempLabel = null;

            // 表體輸出
            int bodyLen = body.length;
            // 循環寫入表體內容
            for (int j = 0; j < bodyLen; j++) {
                String[] bodyTempArr = data.get(j);
                for (int k = 0; k < bodyTempArr.length; k++) {
                    WritableCellFormat tempCellFormat = null;
                    tempCellFormat = getBodyCellStyle();
                    if (tempCellFormat != null) {
                        if (k == 0 || k == (bodyTempArr.length - 1)) {
                            tempCellFormat.setAlignment(Alignment.CENTRE);
                        }
                    }
                    tempLabel = new Label(1 + k, 2 + j, bodyTempArr[k], tempCellFormat);
                    sheet.addCell(tempLabel);
                }
            }
            book.write();
            book.close();
        } catch (IOException e) {
            createFlag = false;
            System.out.println("EXCEL創建失敗!");
            e.printStackTrace();
        } catch (RowsExceededException e) {
            createFlag = false;
            System.out.println("EXCEL單元設置創建失敗!");
            e.printStackTrace();
        } catch (WriteException e) {
            createFlag = false;
            System.out.println("EXCEL寫入失敗!");
            e.printStackTrace();
        }

        return createFlag;
    }

    public WritableCellFormat getHeaderCellStyle() {
        WritableFont font = new WritableFont(WritableFont.createFont("宋體"), 10, WritableFont.BOLD, false,
                UnderlineStyle.NO_UNDERLINE);
        WritableCellFormat headerFormat = new WritableCellFormat(NumberFormats.TEXT);
        try {
            // 添加字體設置
            headerFormat.setFont(font);
            // 設置單元格背景色:表頭為黃色
            headerFormat.setBackground(Colour.YELLOW);
            // 設置表頭表格邊框樣式
            // 整個表格線為粗線、黑色
            headerFormat.setBorder(Border.ALL, BorderLineStyle.THICK, Colour.BLACK);
            // 表頭內容水平居中顯示
            headerFormat.setAlignment(Alignment.CENTRE);
        } catch (WriteException e) {
            System.out.println("表頭單元格樣式設置失敗!");
        }
        return headerFormat;
    }

    public WritableCellFormat getBodyCellStyle() {
        WritableFont font = new WritableFont(WritableFont.createFont("宋體"), 10, WritableFont.NO_BOLD, false,
                UnderlineStyle.NO_UNDERLINE);
        WritableCellFormat bodyFormat = new WritableCellFormat(font);
        try {
            // 設置單元格背景色:表體為白色
            bodyFormat.setBackground(Colour.WHITE);
            // 設置表頭表格邊框樣式
            // 整個表格線為細線、黑色
            bodyFormat.setBorder(Border.ALL, BorderLineStyle.THIN, Colour.BLACK);
        } catch (WriteException e) {
            System.out.println("表體單元格樣式設置失敗!");
        }
        return bodyFormat;
    }

    /**
     * 讀取Excel的內容,第一維數組存儲的是一行中格列的值,二維數組存儲的是多少個行
     * 
     * @param file
     *            讀取數據的源Excel
     * @param ignoreRows
     *            讀取數據忽略的行數,比喻行頭不需要讀入 忽略的行數為1
     * @return 讀出的Excel中數據的內容
     * @throws FileNotFoundException
     * @throws IOException
     */
    public static List<String[]> getData(File file, int ignoreRows) throws FileNotFoundException, IOException {
        List<String[]> result = new ArrayList<String[]>();
        int rowSize = 0;
        BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
        // 打開HSSFWorkbook
        POIFSFileSystem fs = new POIFSFileSystem(in);
        HSSFWorkbook wb = new HSSFWorkbook(fs);
        HSSFCell cell = null;
        for (int sheetIndex = 0; sheetIndex < wb.getNumberOfSheets(); sheetIndex++) {// getNumberOfSheets:讀取sheet的數量
            HSSFSheet st = wb.getSheetAt(sheetIndex);// 第一個sheet
            // 第一行為標題,不取rowIndex=1
            for (int rowIndex = ignoreRows; rowIndex <= st.getLastRowNum(); rowIndex++) {// 每一行的數據存入一個數組中,再將這個數組加入到一個list中
                HSSFRow row = st.getRow(rowIndex);
                if (row == null) {
                    continue;
                }
                int tempRowSize = row.getLastCellNum() + 1;
                if (tempRowSize > rowSize) {
                    rowSize = tempRowSize;
                }
                String[] values = new String[rowSize];// 以列數為大小創建一個String數組對其中的每個元素並賦值空字符串
                Arrays.fill(values, "");
                boolean hasValue = false;
                for (short columnIndex = 0; columnIndex <= row.getLastCellNum(); columnIndex++) {
                    String value = "";
                    cell = row.getCell(columnIndex);// 取這一行的每一個單元格
                    if (cell != null) {
                        // 注意:一定要設成這個,否則可能會出現亂碼
                        cell.setEncoding(HSSFCell.ENCODING_UTF_16);
                        switch (cell.getCellType()) {// 根據每個單元格的數據類型取值
                        case HSSFCell.CELL_TYPE_STRING:
                            value = cell.getStringCellValue();
                            break;
                        case HSSFCell.CELL_TYPE_NUMERIC:
                            if (HSSFDateUtil.isCellDateFormatted(cell)) {
                                Date date = cell.getDateCellValue();
                                if (date != null) {
                                    value = new SimpleDateFormat("yyyy-MM-dd").format(date);
                                } else {
                                    value = "";
                                }
                            } else {
                                value = new DecimalFormat("0").format(cell.getNumericCellValue());
                            }
                            break;
                        case HSSFCell.CELL_TYPE_FORMULA:
                            // 導入時如果為公式生成的數據則無值
                            if (!cell.getStringCellValue().equals("")) {
                                value = cell.getStringCellValue();
                            } else {
                                value = cell.getNumericCellValue() + "";
                            }
                            break;
                        case HSSFCell.CELL_TYPE_BLANK:
                            break;
                        case HSSFCell.CELL_TYPE_ERROR:
                            value = "";
                            break;
                        case HSSFCell.CELL_TYPE_BOOLEAN:
                            value = (cell.getBooleanCellValue() == true ? "Y" : "N");
                            break;
                        default:
                            value = "";
                        }
                    }
                    if (columnIndex == 0 && value.trim().equals("")) {
                        break;
                    }
                    values[columnIndex] = rightTrim(value);
                    hasValue = true;
                }

                if (hasValue) {
                    result.add(values);
                }
            }
        }
        in.close();
//      String[][] returnArray = new String[result.size()][rowSize];
//      for (int i = 0; i < returnArray.length; i++) {
//          returnArray[i] = (String[]) result.get(i);
//      }
        return result;
    }

    /**
     * 去掉字符串右邊的空格
     * 
     * @param str
     *            要處理的字符串
     * @return 處理後的字符串
     */
    public static String rightTrim(String str) {
        if (str == null) {
            return "";
        }
        int length = str.length();
        for (int i = length - 1; i >= 0; i--) {
            if (str.charAt(i) != 0x20) {
                break;
            }
            length--;
        }
        return str.substring(0, length);
    }

    public static void main(String[] args) throws Exception {
        File file = new File("F:/tomcat7/webapps/Excel/upload/3.xls");
        List<String[]> result = getData(file, 1);
//      int rowLength = result.length;
//      for (int i = 0; i < rowLength; i++) {
//          for (int j = 0; j < result[i].length; j++) {
//              System.out.print(result[i][j] + "\t\t");
//          }
//          System.out.println();
//      }
//      String[][] body = result; // 如何傳值?

        String filePath = "F:/tomcat7/webapps/Excel/upload/3333.xls";

        boolean flag = jxlTable.createTable(result, filePath); ///// 傳個List
        if (flag) {
            System.out.println("表格創建成功!!");
        }
    }
}
xuxiaoyinliu
kristenlee1218
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved