java读取excel文件
❶ java如何读取整个excel文件的内容
在java程序添加spire.xls.jar依赖
importcom.spire.xls.*;
publicclassReadExcel{
publicstaticvoidmain(String[]args){
//创建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(" ");
}
}
}
❷ java怎么读取上传的excel文件
java怎么读取上传的excel文件,解决办法:
添加jar文件,java导入导出Excel文件要引入jxl.jar包,最关键的是这套API是纯Java的,并不依赖Windows系统,即使运行在Linux下,它同样能够正确的处理Excel文件。
jxl对Excel表格的认识,每个单元格的位置认为是由一个二维坐标(i,j)给定,其中i表示列,如岁j表示行,并且从上到下递增,从左到右递增。
对于合并单元格的以最左,最上的单元格的坐标为准。如下图中t.xls,一班名单(0,0),陈茵(1,2),陈开先(1,6)。
4.java代码对t.xls的读取
❸ 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();
}
}
}
❹ java中怎样从Excel中读写数据
JavaEXCELAPI简介
JavaExcel是一开放源码项目,通过它Java开发人员可以读取Excel文件的内容、创建新的Excel文件、更新已经存在的Excel文件。使用该API非Windows操作系统也可以通过纯Java应用来处理Excel数据表。因为是使用Java编写的,所以我们在Web应用中可以通过JSP、Servlet来调用API实现对Excel数据表的访问。
应用示例
从Excel文件读取数据表
Java ExcelAPI既可以从本地文件系统的一个文件(.xls),也可以从输入流中读取Excel数据表。读取Excel数据表的第一步是创建Workbook(术语:工作薄),下面的代码片段举例说明了应该如何操作: 需要用到一个开源的jar包,jxl.jar。
Filefile=newFile("c:\a.xls");
InputStreamin=newFileInputStream(file);
Workbookworkbook=Workbook.getWorkbook(in);
//获取第一张Sheet表
Sheetsheet=workbook.getSheet(0);
//我们既可能通过Sheet的名称来访问它,也可以通过下标来访问它。如果通过下标来访问的话,要注意的一点是下标从0开始,就像数组一样。
//获取第一行,第一列的值
Cellc00=rs.getCell(0,0);
Stringstrc00=c00.getContents();
//获取第一行,第二列的值
Cellc10=rs.getCell(1,0);
Stringstrc10=c10.getContents();
//我们可以通过指定行和列得到指定的单元格Cell对象
Cellcell=sheet.getCell(column,row);
//也可以得到某一行或者某一列的所有单元格Cell对象
Cell[]cells=sheet.getColumn(column);
Cell[]cells2=sheet.getRow(row);
//然后再取每一个Cell中的值
Stringcontent=cell.getContents();
❺ java怎么读取excel文件
参考代码及注释如下:
importJava.io.File;
importjava.io.FileInputStream;
importjava.io.FileNotFoundException;
importjava.io.IOException;
importjava.io.InputStream;
importorg.apache.poi.hssf.usermodel.HSSFWorkbook;
importorg.apache.poi.ss.usermodel.Cell;
importorg.apache.poi.ss.usermodel.Row;
importorg.apache.poi.ss.usermodel.Sheet;
importorg.apache.poi.ss.usermodel.Workbook;
publicclassReadExcel{
publicstaticvoidreadExcel(Filefile){
try{
InputStreaminputStream=newFileInputStream(file);
StringfileName=file.getName();
Workbookwb=null;
//poi-3.9.jar只可以读取2007以下的版本,后缀为:xsl
wb=newHSSFWorkbook(inputStream);//解析xls格式
Sheetsheet=wb.getSheetAt(0);//第一个工作表,第二个则为1,以此类推...
intfirstRowIndex=sheet.getFirstRowNum();
intlastRowIndex=sheet.getLastRowNum();
for(intrIndex=firstRowIndex;rIndex<=lastRowIndex;rIndex++){
Rowrow=sheet.getRow(rIndex);
if(row!=null){
intfirstCellIndex=row.getFirstCellNum();
//intlastCellIndex=row.getLastCellNum();
//此处参数cIndex决定可以取到excel的列数。
for(intcIndex=firstCellIndex;cIndex<3;cIndex++){
Cellcell=row.getCell(cIndex);
Stringvalue="";
if(cell!=null){
value=cell.toString();
System.out.print(value+" ");
}
}
System.out.println();
}
}
}catch(FileNotFoundExceptione){
//TODO自动生成catch块
e.printStackTrace();
}catch(IOExceptione){
//TODO自动生成catch块
e.printStackTrace();
}
}
publicstaticvoidmain(String[]args){
Filefile=newFile("D:/test.xls");
readExcel(file);
}
}
❻ java读取和输出excel表格的问题
Java Excel 是一个开源项目,通过它Java开发人员可以读取Excel文件的内容、创建新的Excel文件、更新已经存在的Excel文件等,在项目中需要导入名为jxl.jar的包。在这里只是示例它的基本用法,其他高级的功能(图片、公式、格式等)请参考Java Excel的帮助文档。
如有一个用户资料的Excel表,包含ID、用户名、性别、邮件等信息,定义一个用户JavaBean:
packagecom.monitor1394.excel;
/**
*
*用户
*
*@authormonitor
*Createdon2010-12-22,9:57:58
*/
publicclassUser{
/**ID*/
privateintid;
/**用户名*/
privateStringname;
/**性别1:男2:女*/
privateintsex;
/**邮件*/
privateStringemail;
publicUser(){
}
publicUser(intid,Stringname,intsex,Stringemail){
this.id=id;
this.name=name;
this.sex=sex;
this.email=email;
}
publicStringgetEmail(){
returnemail;
}
publicvoidsetEmail(Stringemail){
this.email=email;
}
publicintgetId(){
returnid;
}
publicvoidsetId(intid){
this.id=id;
}
publicStringgetName(){
returnname;
}
publicvoidsetName(Stringname){
this.name=name;
}
publicintgetSex(){
returnsex;
}
publicvoidsetSex(intsex){
this.sex=sex;
}
@Override
publicStringtoString(){
returnid+":"+name;
}
}
提供的Excel表操作类如下,某些单元格的格式可按自己意愿指定:
packagecom.monitor1394.excel;
importjava.io.File;
importjava.io.IOException;
importjava.util.ArrayList;
importjava.util.List;
importjxl.Sheet;
importjxl.Workbook;
importjxl.format.Alignment;
importjxl.format.Border;
importjxl.format.BorderLineStyle;
importjxl.format.Colour;
importjxl.format.VerticalAlignment;
importjxl.read.biff.BiffException;
importjxl.write.Label;
importjxl.write.Number;
importjxl.write.NumberFormats;
importjxl.write.WritableCellFormat;
importjxl.write.WritableFont;
importjxl.write.WritableSheet;
importjxl.write.WritableWorkbook;
importjxl.write.WriteException;
/**
*
*Excel表操作
*
*@authormonitor
*Createdon2010-12-22,9:50:28
*/
publicclassExcel{
/**标题单元格格式*/
=null;
/**主题内容单元格格式*/
=null;
/**注释单元格格式*/
=null;
/**浮点型数据的单元格格式*/
=null;
/**整型数据的单元格格式*/
=null;
/**初始化数据*/
privatestaticbooleaninit=false;
/**私有构造方法,防止错误使用Excel类*/
privateExcel(){
}
/**
*初始化各单元格格式
*@throwsWriteException初始化失败
*/
privatestaticvoidinit()throwsWriteException{
WritableFontfont1,font2,font3,font4;
//Arial字体,9号,粗体,单元格黄色,田字边框,居中对齐
font1=newWritableFont(WritableFont.ARIAL,9,WritableFont.BOLD,false);
titleFormat=newWritableCellFormat(font1);
titleFormat.setBackground(Colour.YELLOW);
titleFormat.setBorder(Border.ALL,BorderLineStyle.THIN);
titleFormat.setAlignment(Alignment.CENTRE);
//Arial字体,9号,粗体,单元格黄色,田字边框,左右居中对齐,垂直居中对齐,自动换行
font2=newWritableFont(WritableFont.ARIAL,9,WritableFont.BOLD,false);
noteFormat=newWritableCellFormat(font2);
noteFormat.setBackground(Colour.YELLOW);
noteFormat.setBorder(Border.ALL,BorderLineStyle.THIN);
noteFormat.setAlignment(Alignment.CENTRE);
noteFormat.setVerticalAlignment(VerticalAlignment.CENTRE);
noteFormat.setWrap(true);
//Arial字体,9号,非粗体,单元格淡绿色,田字边框
font3=newWritableFont(WritableFont.ARIAL,9,WritableFont.NO_BOLD,false);
bodyFormat=newWritableCellFormat(font3);
bodyFormat.setBackground(Colour.LIGHT_GREEN);
bodyFormat.setBorder(Border.ALL,BorderLineStyle.THIN);
//Arial字体,9号,非粗体,单元格淡绿色,田字边框
font4=newWritableFont(WritableFont.ARIAL,9,WritableFont.NO_BOLD,false);
floatFormat=newWritableCellFormat(font4,NumberFormats.FLOAT);
floatFormat.setBackground(Colour.LIGHT_GREEN);
floatFormat.setBorder(Border.ALL,BorderLineStyle.THIN);
//Arial字体,9号,非粗体,单元格淡绿色,田字边框
font4=newWritableFont(WritableFont.ARIAL,9,WritableFont.NO_BOLD,false);
intFormat=newWritableCellFormat(font4,NumberFormats.INTEGER);
intFormat.setBackground(Colour.LIGHT_GREEN);
intFormat.setBorder(Border.ALL,BorderLineStyle.THIN);
init=true;
}
(List<User>userList,FiledestFile)throwsWriteException,IOException{
if(init==false)init();
intindex,row;
WritableSheetsheet=null;
WritableWorkbookbook=null;
book=Workbook.createWorkbook(destFile);
sheet=book.createSheet("用户表",0);
sheet.setColumnView(0,15);
sheet.setColumnView(1,15);
sheet.setColumnView(2,15);
sheet.setColumnView(3,40);
//字段变量名
index=0;
sheet.addCell(newLabel(index++,0,"id",titleFormat));
sheet.addCell(newLabel(index++,0,"name",titleFormat));
sheet.addCell(newLabel(index++,0,"sex",titleFormat));
sheet.addCell(newLabel(index++,0,"email",titleFormat));
//字段名
index=0;
sheet.addCell(newLabel(index++,1,"ID",titleFormat));
sheet.addCell(newLabel(index++,1,"用户名",titleFormat));
sheet.addCell(newLabel(index++,1,"性别",titleFormat));
sheet.addCell(newLabel(index++,1,"邮件",titleFormat));
//字段注释
index=0;
sheet.addCell(newLabel(index++,2,null,noteFormat));
sheet.addCell(newLabel(index++,2,null,noteFormat));
sheet.addCell(newLabel(index++,2,"1:男/n2:女",noteFormat));
sheet.addCell(newLabel(index++,2,null,noteFormat));
row=3;
for(Useruser:userList){
if(user==null)continue;
index=0;
sheet.addCell(newNumber(index++,row,user.getId(),bodyFormat));
sheet.addCell(newLabel(index++,row,user.getName(),bodyFormat));
sheet.addCell(newNumber(index++,row,user.getSex(),bodyFormat));
sheet.addCell(newLabel(index++,row,user.getEmail(),bodyFormat));
row++;
}
book.write();
if(book!=null)book.close();
}
publicstaticList<User>readUserExcelFile(Filefile)throwsIOException,BiffException{
if(file==null)returnnull;
introw,column;
Stringtemp=null;
Workbookbook=null;
Sheetsheet=null;
List<User>userList=newArrayList<User>();
book=Workbook.getWorkbook(file);
sheet=book.getSheet(0);
row=3;
while(row<sheet.getRows()){
column=0;
Useruser=newUser();
//id
temp=sheet.getCell(column++,row).getContents().trim();
if(temp!=null&&!temp.equals("")&&temp.matches("//d+"))user.setId(Integer.parseInt(temp));
elsebreak;
//名称
temp=sheet.getCell(column++,row).getContents().trim();
if(temp!=null&&!temp.equals(""))user.setName(temp);
//性别
temp=sheet.getCell(column++,row).getContents().trim();
if(temp!=null&&!temp.equals("")&&temp.matches("//d+"))user.setSex(Integer.parseInt(temp));
//邮件
temp=sheet.getCell(column++,row).getContents().trim();
if(temp!=null&&!temp.equals(""))user.setEmail(temp);
userList.add(user);
row++;
}
if(book!=null)book.close();
returnuserList;
}
}
要导入的Excel表格式如下:
❼ 如何用JAVA读取EXCEL文件里面的数据
使用poi能解决你的问题
或者是
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import static java.lang.System.out;
public class FileTest {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
String string = "";
File file = new File("c:" + File.separator + "xxx.xls");
FileReader fr = new FileReader(file);
BufferedReader br = new BufferedReader(fr);
String str;
while((str = br.readLine()) != null) {
string += str;
}
out.println(string);
}
}