A. 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;i<rowLength;i++) {
for(int j=0;j<result[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 {
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);
}
}
B. java怎麼讀取excel數據
引入poi的jar包,大致如下:
importjava.io.FileInputStream;
importjava.io.FileNotFoundException;
importjava.io.IOException;
importjava.io.InputStream;
importjava.math.BigDecimal;
importjava.text.DecimalFormat;
importjava.text.SimpleDateFormat;
importorg.apache.poi.xssf.usermodel.XSSFCell;
importorg.apache.poi.xssf.usermodel.XSSFRow;
importorg.apache.poi.xssf.usermodel.XSSFSheet;
importorg.apache.poi.xssf.usermodel.XSSFWorkbook;
publicclassExcelUtil2007{
/**讀取excel文件流的指定索引的sheet
*@paraminputStreamexcel文件流
*@paramsheetIndex要讀取的sheet的索引
*@return
*@throwsFileNotFoundException
*@throwsIOException
*/
(InputStreaminputStream,intsheetIndex)throwsFileNotFoundException,IOException
{
returnreadExcel(inputStream).getSheetAt(sheetIndex);
}
/**讀取excel文件的指定索引的sheet
*@paramfilePathexcel文件路徑
*@paramsheetIndex要讀取的sheet的索引
*@return
*@throwsIOException
*@throwsFileNotFoundException
*/
(StringfilePath,intsheetIndex)throwsFileNotFoundException,IOException
{
returnreadExcel(filePath).getSheetAt(sheetIndex);
}
/**讀取excel文件的指定索引的sheet
*@paramfilePathexcel文件路徑
*@paramsheetName要讀取的sheet的名稱
*@return
*@throwsIOException
*@throwsFileNotFoundException
*/
(StringfilePath,StringsheetName)throwsFileNotFoundException,IOException
{
returnreadExcel(filePath).getSheet(sheetName);
}
/**讀取excel文件,返回XSSFWorkbook對象
*@paramfilePathexcel文件路徑
*@return
*@throwsFileNotFoundException
*@throwsIOException
*/
(StringfilePath)throwsFileNotFoundException,IOException
{
XSSFWorkbookwb=newXSSFWorkbook(newFileInputStream(filePath));
returnwb;
}
/**讀取excel文件流,返回XSSFWorkbook對象
*@paraminputStreamexcel文件流
*@return
*@throwsFileNotFoundException
*@throwsIOException
*/
(InputStreaminputStream)throwsFileNotFoundException,IOException
{
XSSFWorkbookwb=newXSSFWorkbook(inputStream);
returnwb;
}
/***讀取excel中指定的單元格,並返回字元串形式的值
*1.數字
*2.字元
*3.公式(返回的為公式內容,非單元格的值)
*4.空
*@paramst要讀取的sheet對象
*@paramrowIndex行索引
*@paramcolIndex列索引
*@paramisDate是否要取的是日期(是則返回yyyy-MM-dd格式的字元串)
*@return
*/
(XSSFSheetst,introwIndex,intcolIndex,booleanisDate){
Strings="";
XSSFRowrow=st.getRow(rowIndex);
if(row==null)return"";
XSSFCellcell=row.getCell(colIndex);
if(cell==null)return"";
if(cell.getCellType()==0){//數字
if(isDate)s=newSimpleDateFormat("yyyy-MM-dd").format(cell.getDateCellValue());
elses=trimPointO(String.valueOf(getStringValue(cell)).trim());
}elseif(cell.getCellType()==1){//字元(excel中的空格,不是全形,也不是半形,不知道是神馬,反正就是""這個)
s=cell.getRichStringCellValue().getString().replaceAll("","").trim();
// s=cell.getStringCellValue();//07API新增,好像跟上一句一致
}
elseif(cell.getCellType()==2){//公式
s=cell.getCellFormula();
}
elseif(cell.getCellType()==3){//空
s="";
}
returns;
}
/**如果數字以.0結尾,則去掉.0
*@params
*@return
*/
publicstaticStringtrimPointO(Strings){
if(s.endsWith(".0"))
returns.substring(0,s.length()-2);
else
returns;
}
/**處理科學計數法和百分比模式的數字單元格
*@paramcell
*@return
*/
(XSSFCellcell){
StringsValue=null;
shortdataFormat=cell.getCellStyle().getDataFormat();
doubled=cell.getNumericCellValue();
BigDecimalb=newBigDecimal(Double.toString(d));
//百分比樣式的
if(dataFormat==0xa||dataFormat==9){
b=b.multiply(newBigDecimal(100));
//Stringtemp=b.toPlainString();
DecimalFormatdf=newDecimalFormat("0.00");//保留兩位小數的百分比格式
sValue=df.format(b)+"%";
}else{
sValue=b.toPlainString();
}
returnsValue;
}
}
C. 淺談JAVA讀寫Excel的幾種途徑
讀寫Excel文件需要使用Excel類庫,如Free Spire.XLS for Java.
讀取Excel內容:
//創建Workbook對象
Workbookwb=newWorkbook();
//載入一個Excel文檔
wb.loadFromFile("C:\Users\Administrator\Desktop\test.xlsx");
//獲取第一個工作表
Worksheetsheet=wb.getWorksheets().get(0);
//遍歷工作表的每一行
for(inti=1;i<sheet.getLastRow()+1;i++){
//遍歷工作的每一列
for(intj=1;j<sheet.getLastColumn()+1;j++){
//輸出指定單元格的數據
System.out.print(sheet.get(i,j).getText());
System.out.print(" ");
}
System.out.print(" ");
}
寫入內容:
//創建Workbook對象
Workbookwb=newWorkbook();
//載入一個Excel文檔
wb.loadFromFile("C:\Users\Administrator\Desktop\test.xlsx");
//獲取第一個工作表
Worksheetsheet=wb.getWorksheets().get(0);
//在單元格A1寫入新數據
sheet.getCellRange("A1").setText("你好");
//保存文檔
wb.saveToFile("寫入Excel.xlsx",ExcelVersion.Version2016);
D. java中怎麼讀取excel文件
package com.jqgj.test;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.io.FilenameUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellValue;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.FormulaEvaluator;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ImportNameTest {
/**
* Excel 2003
*/
private final static String XLS = "xls";
/**
* Excel 2007
*/
private final static String XLSX = "xlsx";
/**
* 分隔符
*/
private final static String SEPARATOR = "|";
/**
* 由Excel文件的Sheet導出至List
*
* @param file
* @param sheetNum
* @return
*/
public static List<String> exportListFromExcel(File file, int sheetNum)
throws IOException {
return exportListFromExcel(new FileInputStream(file),
FilenameUtils.getExtension(file.getName()), sheetNum);
}
/**
* 由Excel流的Sheet導出至List
*
* @param is
* @param extensionName
* @param sheetNum
* @return
* @throws IOException
*/
public static List<String> exportListFromExcel(InputStream is,
String extensionName, int sheetNum) throws IOException {
Workbook workbook = null;
if (extensionName.toLowerCase().equals(XLS)) {
workbook = new HSSFWorkbook(is);
} else if (extensionName.toLowerCase().equals(XLSX)) {
workbook = new XSSFWorkbook(is);
}
return exportListFromExcel(workbook, sheetNum);
}
/**
* 由指定的Sheet導出至List
*
* @param workbook
* @param sheetNum
* @return
* @throws IOException
*/
private static List<String> exportListFromExcel(Workbook workbook,
int sheetNum) {
Sheet sheet = workbook.getSheetAt(sheetNum);
// 解析公式結果
FormulaEvaluator evaluator = workbook.getCreationHelper()
.createFormulaEvaluator();
List<String> list = new ArrayList<String>();
int minRowIx = sheet.getFirstRowNum();
int maxRowIx = sheet.getLastRowNum();
for (int rowIx = minRowIx; rowIx <= maxRowIx; rowIx++) {
Row row = sheet.getRow(rowIx);
StringBuilder sb = new StringBuilder();
short minColIx = row.getFirstCellNum();
short maxColIx = row.getLastCellNum();
for (short colIx = minColIx; colIx <= maxColIx; colIx++) {
Cell cell = row.getCell(new Integer(colIx));
CellValue cellValue = evaluator.evaluate(cell);
if (cellValue == null) {
continue;
}
// 經過公式解析,最後只存在Boolean、Numeric和String三種數據類型,此外就是Error了
// 其餘數據類型,根據官方文檔,完全可以忽略http://poi.apache.org/spreadsheet/eval.html
switch (cellValue.getCellType()) {
case Cell.CELL_TYPE_BOOLEAN:
sb.append(SEPARATOR + cellValue.getBooleanValue());
break;
case Cell.CELL_TYPE_NUMERIC:
// 這里的日期類型會被轉換為數字類型,需要判別後區分處理
if (DateUtil.isCellDateFormatted(cell)) {
sb.append(SEPARATOR + cell.getDateCellValue());
} else {
//把手機號碼轉換為字元串
DecimalFormat df = new DecimalFormat("#");
sb.append(SEPARATOR + df.format(cellValue.getNumberValue()));
}
break;
case Cell.CELL_TYPE_STRING:
sb.append(SEPARATOR + cellValue.getStringValue());
break;
case Cell.CELL_TYPE_FORMULA:
break;
case Cell.CELL_TYPE_BLANK:
break;
case Cell.CELL_TYPE_ERROR:
break;
default:
break;
}
}
list.add(sb.toString());
}
return list;
}
/**
* @param args
*/
public static void main(String[] args) {
String path = "f:\\telName.xlsx";
try {
List<String> listS= exportListFromExcel(new File(path),0);
for(int i=0;i<listS.size();i++){
System.out.println(listS.get(i));
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
E. Java中poi讀取含有失效超鏈接的Excel2007報錯
你好,這個問題我遇到過:
你需要做兩件事情
超鏈接內不同時使用#$%^中任意3 個。
取消此時的超鏈接
解決方案:
你對讀取到的每一個cell的值做一下判斷,如果含有#$%^中的連續三個,你就做一些異常捕獲
利用如下代碼取消超鏈接
if(cell.getHyperlink() != null) {
cell.setHyperlink(null);
}
希望能幫助到你!!有問題繼續追問,滿意請採納!!
F. java poi讀取Excel2007 的問題
你的郵箱 被服務商限制,超過1兆的郵件都收不了。。。。。。.jar包有1.4兆。
我都編輯好了,看到速度給我發QQ郵件: [email protected] ,我再重新給你郵