java中讀取excel文件,java 讀取 excel

本文目錄一覽:

java怎麼讀取excel數據

引入poi的jar包,大致如下:

讀取代碼如下,應該能看得明白吧

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.IOException;

import java.io.InputStream;

import java.math.BigDecimal;

import java.text.DecimalFormat;

import java.text.SimpleDateFormat;

import org.apache.poi.xssf.usermodel.XSSFCell;

import org.apache.poi.xssf.usermodel.XSSFRow;

import org.apache.poi.xssf.usermodel.XSSFSheet;

import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class ExcelUtil2007 {

/**讀取excel文件流的指定索引的sheet

 * @param inputStream excel文件流

 * @param sheetIndex 要讀取的sheet的索引

 * @return

 * @throws FileNotFoundException

 * @throws IOException

 */

public static XSSFSheet readExcel(InputStream inputStream,int sheetIndex) throws FileNotFoundException, IOException

{

return readExcel(inputStream).getSheetAt(sheetIndex);

}

/**讀取excel文件的指定索引的sheet

 * @param filePath excel文件路徑

 * @param sheetIndex 要讀取的sheet的索引

 * @return

 * @throws IOException 

 * @throws FileNotFoundException 

 */

public static XSSFSheet readExcel(String filePath,int sheetIndex) throws FileNotFoundException, IOException

{

return readExcel(filePath).getSheetAt(sheetIndex);

}

/**讀取excel文件的指定索引的sheet

 * @param filePath excel文件路徑

 * @param sheetName 要讀取的sheet的名稱

 * @return

 * @throws IOException 

 * @throws FileNotFoundException 

 */

public static XSSFSheet readExcel(String filePath,String sheetName) throws FileNotFoundException, IOException

{

return readExcel(filePath).getSheet(sheetName);

}

/**讀取excel文件,返回XSSFWorkbook對象

 * @param filePath excel文件路徑

 * @return 

 * @throws FileNotFoundException

 * @throws IOException

 */

public static XSSFWorkbook readExcel(String filePath) throws FileNotFoundException, IOException

{

XSSFWorkbook wb=new XSSFWorkbook(new FileInputStream(filePath));

return wb;

}

/**讀取excel文件流,返回XSSFWorkbook對象

 * @param inputStream excel文件流

 * @return

 * @throws FileNotFoundException

 * @throws IOException

 */

public static XSSFWorkbook readExcel(InputStream inputStream) throws FileNotFoundException, IOException

{

XSSFWorkbook wb=new XSSFWorkbook(inputStream);

return wb;

}

/***讀取excel中指定的單元格,並返回字符串形式的值

 * 1.數字

 * 2.字符

 * 3.公式(返回的為公式內容,非單元格的值)

 * 4.空

 * @param st 要讀取的sheet對象

 * @param rowIndex 行索引

 * @param colIndex 列索引

 * @param isDate 是否要取的是日期(是則返回yyyy-MM-dd格式的字符串)

 * @return

 */

public static String getCellString(XSSFSheet st,int rowIndex,int colIndex,boolean isDate){

String s=””;

XSSFRow row=st.getRow(rowIndex);

if(row == null) return “”;

XSSFCell cell=row.getCell(colIndex);

if(cell == null) return “”;

if (cell.getCellType() == 0) {//數字

if(isDate)s=new SimpleDateFormat(“yyyy-MM-dd”).format(cell.getDateCellValue());

else s = trimPointO(String.valueOf(getStringValue(cell)).trim());

}else if (cell.getCellType() == 1){//字符(excel中的空格,不是全角,也不是半角,不知道是神馬,反正就是” “這個)

s=cell.getRichStringCellValue().getString().replaceAll(” “, ” “).trim();

// s=cell.getStringCellValue();//07API新增,好像跟上一句一致

}

else if (cell.getCellType() == 2){//公式

s=cell.getCellFormula();

}

else if (cell.getCellType() == 3){//空

s=””;

}

return s;

}

/**如果數字以 .0 結尾,則去掉.0

 * @param s

 * @return

 */

public static String trimPointO(String s) {

if (s.endsWith(“.0”))

return s.substring(0, s.length() – 2);

else

return s;

}

/**處理科學計數法和百分比模式的數字單元格

 * @param cell

 * @return

 */

public static String getStringValue(XSSFCell cell) {

String sValue = null;

short dataFormat = cell.getCellStyle().getDataFormat();

double d = cell.getNumericCellValue();

BigDecimal b = new BigDecimal(Double.toString(d));

//百分比樣式的

if (dataFormat == 0xa || dataFormat == 9) {

b=b.multiply(new BigDecimal(100));

//String temp=b.toPlainString();

DecimalFormat df=new DecimalFormat(“0.00”);//保留兩位小數的百分比格式

sValue = df.format(b) + “%”;

}else{

sValue = b.toPlainString();

}

return sValue;

}

}

java中怎樣從Excel中讀寫數據

Java EXCEL API簡介 

Java Excel是一開放源碼項目,通過它Java開發人員可以讀取Excel文件的內容、創建新的Excel文件、更新已經存在的Excel文件。使用該API非Windows操作系統也可以通過純Java應用來處理Excel數據表。因為是使用Java編寫的,所以我們在Web應用中可以通過JSP、Servlet來調用API實現對Excel數據表的訪問。

應用示例 

從Excel文件讀取數據表 

Java Excel API既可以從本地文件系統的一個文件(.xls),也可以從輸入流中讀取Excel數據表。讀取Excel數據表的第一步是創建Workbook(術語:工作薄),下面的代碼片段舉例說明了應該如何操作:  需要用到一個開源的jar包,jxl.jar。

File file = new File(“c:\\a.xls”);  

InputStream in = new FileInputStream(file);  

Workbook workbook = Workbook.getWorkbook(in);  

//獲取第一張Sheet表  

Sheet sheet = workbook.getSheet(0);  

  

//我們既可能通過Sheet的名稱來訪問它,也可以通過下標來訪問它。如果通過下標來訪問的話,要注意的一點是下標從0開始,就像數組一樣。  

//獲取第一行,第一列的值   

Cell c00 = rs.getCell(0, 0);   

String strc00 = c00.getContents();   

//獲取第一行,第二列的值   

Cell c10 = rs.getCell(1, 0);   

String strc10 = c10.getContents();   

//我們可以通過指定行和列得到指定的單元格Cell對象  

  Cell cell = sheet.getCell(column, row);  

  //也可以得到某一行或者某一列的所有單元格Cell對象  

  Cell[] cells = sheet.getColumn(column);  

  Cell[] cells2 = sheet.getRow(row);  

  //然後再取每一個Cell中的值  

  String content = cell.getContents();

怎麼用java代碼讀取excel文件

本例使用java來讀取excel的內容並展出出結果,代碼如下:

複製代碼 代碼如下:

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;

public class ExcelOperate {

public static void main(String[] args) throws Exception {

File file = new File(“ExcelDemo.xls”);

String[][] result = getData(file, 1);

int rowLength = result.length;

for(int i=0;irowLength;i++) {

for(int j=0;jresult[i].length;j++) {

System.out.print(result[i][j]+”\t\t”);

}

System.out.println();

}

}

/**

* 讀取Excel的內容,第一維數組存儲的是一行中格列的值,二維數組存儲的是多少個行

* @param file 讀取數據的源Excel

* @param ignoreRows 讀取數據忽略的行數,比喻行頭不需要讀入 忽略的行數為1

* @return 讀出的Excel中數據的內容

* @throws FileNotFoundException

* @throws IOException

*/

public static String[][] getData(File file, int ignoreRows)

throws FileNotFoundException, IOException {

ListString[] result = new ArrayListString[]();

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;

}

java如何讀取整個excel文件的內容

工具:

參考代碼及注釋如下:

import Java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; public class ReadExcel { public static void readExcel(File file){ try { InputStream inputStream = new FileInputStream(file); String fileName = file.getName(); Workbook wb = null; // poi-3.9.jar 只可以讀取2007以下的版本,後綴為:xsl wb = new HSSFWorkbook(inputStream);//解析xls格式 Sheet sheet = wb.getSheetAt(0);//第一個工作表 ,第二個則為1,以此類推… int firstRowIndex = sheet.getFirstRowNum(); int lastRowIndex = sheet.getLastRowNum(); for(int rIndex = firstRowIndex; rIndex = lastRowIndex; rIndex ++){ Row row = sheet.getRow(rIndex); if(row != null){ int firstCellIndex = row.getFirstCellNum(); // int lastCellIndex = row.getLastCellNum(); //此處參數cIndex決定可以取到excel的列數。 for(int cIndex = firstCellIndex; cIndex 3; cIndex ++){ Cell cell = row.getCell(cIndex); String value = “”; if(cell != null){ value = cell.toString(); System.out.print(value+”\t”); } } System.out.println(); } } } catch (FileNotFoundException e) { // TODO 自動生成 catch 塊 e.printStackTrace(); } catch (IOException e) { // TODO 自動生成 catch 塊 e.printStackTrace(); } } public static void main(String[] args) { File file = new File(“D:/test.xls”); readExcel(file); }}

原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/243359.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
小藍的頭像小藍
上一篇 2024-12-12 12:56
下一篇 2024-12-12 12:56

相關推薦

發表回復

登錄後才能評論