2 kristenlee1218 kristenlee1218 于 2016.02.20 15:02 提问

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("表格创建成功!!");
    }
}

}

4个回答

xuxiaoyinliu
xuxiaoyinliu   2016.02.20 17:32
已采纳

大概改了下,你试试

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("表格创建成功!!");
        }
    }
}
kristenlee1218
kristenlee1218 回复征途6: 好的 谢谢拉
接近 2 年之前 回复
xuxiaoyinliu
xuxiaoyinliu 回复kristenlee1218: 这个body就是 public boolean createTable(List<String[]>data, String filePath) 方法中的参数中的data,抱歉,忘记改了
接近 2 年之前 回复
kristenlee1218
kristenlee1218 // 表体输出 int bodyLen = body.length; 复制到myeclipse里这个位置报错了
接近 2 年之前 回复
freedamjustice
freedamjustice   2016.02.20 16:56

你方法定义的是一维数组,main方法传参的body是二维数组,当然死报错的了。。。

xuxiaoyinliu
xuxiaoyinliu   2016.02.20 16:49

能否贴点数据啊,不好测试

xuxiaoyinliu
xuxiaoyinliu   2016.02.20 17:14

看你的createTable()方法可以知道,你的参数有问题,如果按照你getData()方法的写法这里应该是 String[][] body而不是 String[]body,这个
问题楼上已经说了,createTable参数有问题
有几个地方建议一下:
1、getData()方法中最后你为什么要把最终结果从list里取出来再放入一个数组中?直接返回这个list不好吗?然后修改下createTable()直接把这个list扔给它处理,看你createTable()的写法也应该是这样的
2、根据你的createTable()中的取值方式可以看到你的每一行数据中的各个单元格数据应该是以","分割的,但在你的getData()方法里我好像没有看到向其中加这个分割符

Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!