怎样用java.jxl实现读取excel的数据?求具体代码(以读取3列为例)

如题所述

import java.io.File;
import java.io.IOException;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;

public class MyExcel {
public static void main(String[] args) {
try {
Workbook workbook = Workbook.getWorkbook(new File("C:\\myfile.xls"));
Sheet sheet = workbook.getSheet(0);//使用第一个工作表
int colnum = sheet.getColumns();//获取列数,如果一定要3列,直接改3就行
int row = sheet.getRows();//获取行数
StringBuffer sb = new StringBuffer();
for(int i=0;i<row;i++){
for(int j=0;j<colnum;j++){
Cell c = sheet.getCell(j,i);//获得单元数据
sb.append(c.getContents()+"\n");
}
}
workbook.close();
System.out.println(sb);
} catch (BiffException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
这个写法有很多种,这里只是给您参考。要读取内容关键是以下几步:
1.创建一个可读取的excel文件对象
Workbook workbook = Workbook.getWorkbook(new File("C:\\myfile.xls"));//注意文件路径
2.获取工作表
Sheet sheet = workbook.getSheet(0);//使用第一个工作表
3.获取单元格数据,我的例子里是通过循环获取所有的数据
sheet.getCell(j,i);
4.最后把获取的数据做你所需要的处理。
sb.append(c.getContents()+"\n");//我这里把它加到了StringBuffer里。
温馨提示:答案为网友推荐,仅供参考
第1个回答  2011-10-19
---------读取EXCEL类
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;

public class ReadExcel
{
public static List<String[]> getSheetMap(File file) throws BiffException, IOException, ServletException
{
Workbook book = Workbook.getWorkbook(file);
Sheet[] sheetList = book.getSheets();// 获得工作表对象数组

String[] mes = null;
Sheet sheets = sheetList[0];
int cols = sheets.getColumns();// col列数
int rows = sheets.getRows();// 行数
int nullcols = 0;
List<String[]> cellList = new ArrayList<String[]>();// NEW一个单元格集合
for (int i = 0; i < rows; i++)
{
mes = new String[cols];// 每一行NEW一个新的列数组,cols是列的长度
nullcols = 0;
for (int j = 0; j < cols; j++)
{
String cur = sheets.getCell(j, i).getContents();// 从EXCEL取得每个单元格中的数据
if (null == cur || "" == cur)
{
nullcols++;
}
mes[j] = cur;// 将单元格的数据存入列数组中
}
if (cols != nullcols)
cellList.add(mes);// 将每列的数组存入每个页的集合中
}

book.close();
return cellList;
}
}追问

在public static void main里面怎么把excel数列中的前三列取出来并赋值给a1a2,a3?

追答

public static void main(String args[]){
List infoList = new ArrayList();
File file = new File("F:\\as.xls");
try {
infoList=ReadExcel.getSheetMap(file);
} catch (BiffException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ServletException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String [] mes = null;
for(int i = 0 ; i< infoList.size() ; i++){
mes = infoList.get(i);
System.out.println(mes[0]);
}
}

本回答被提问者采纳
相似回答