程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 更多編程語言 >> 編程解疑 >> arraylist-急 在線等 謝謝!java想要讀取excel中某以特定單元格的值,現在是循環讀出所有的值,請幫忙修改一下

arraylist-急 在線等 謝謝!java想要讀取excel中某以特定單元格的值,現在是循環讀出所有的值,請幫忙修改一下

編輯:編程解疑
急 在線等 謝謝!java想要讀取excel中某以特定單元格的值,現在是循環讀出所有的值,請幫忙修改一下

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,int rowLength) {
    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;


        String[][] bodyTempArr = body ;
        // 循環寫入表體內容
        for(int i=0;i<rowLength;i++) {
              for(int j=0;j<body[i].length;j++) {
                WritableCellFormat tempCellFormat = null;
                tempCellFormat = getBodyCellStyle();
                if (tempCellFormat != null) {
                    if (j == 0 || j == (bodyTempArr.length - 1)) {
                        tempCellFormat.setAlignment(Alignment.CENTRE);
                    }
                }
                tempLabel = new Label(1 + j, 2 + i, bodyTempArr[i][j],
                        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;
       System.out.println("rowLength="+rowLength);
       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/68.xls";
    JxlTable testJxl = JxlTable.getInstance();
    boolean flag = testJxl.createTable(body, filePath,rowLength);
    if (flag) {
        System.out.println("表格創建成功!!");
    }
}

}

最佳回答:


http://www.cnblogs.com/wuxinrui/archive/2011/03/20/1989326.html,看看這個,在根據自己的需要修改下。

kristenlee1218
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved