㈠ 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.htmlswitch (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 blocke.printStackTrace();}}}
㈡ java打开excel
在JSP页面中输入如下语句就可以了 :<% //设置文件格式和文件名 response.setContentType("Application/msexcel;charset=GBK"); response.setHeader("Content-disposition", "attachment; filename=Allocate Supply by National MAR or Region.xls"); %>
㈢ JAVA读取EXCEL文件
相关功能代码比较多 贴出来不是很方便 我跟你说一下思路吧首先是用到的工具是poi 这个你可以去官网载一个其次 你要注意区分你的excel 是旧的还是新的 office 07版之前和07版之后的 读取的类不一样把握住这2点 差不多就OK了大体的读取流程是读取workbook -> sheet -> row -> col
㈣ 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);elsereturns;}/**处理科学计数法和百分比模式的数字单元格*@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;}}
㈤ 用java读取Excel表格
import java.io.FileInputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.util.ArrayList;import java.util.Date;import java.util.List;import jxl.Cell;import jxl.Sheet;import jxl.Workbook;import jxl.WorkbookSettings;import jxl.format.Alignment;import jxl.format.Border;import jxl.format.BorderLineStyle;import jxl.format.Colour;import jxl.format.VerticalAlignment;import jxl.read.biff.BiffException;import jxl.write.Formula;import jxl.write.Label;import jxl.write.WritableCellFeatures;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;/** * <p>标题:readExcel</p> * <p>描述:读取Excel文件数据</p> * @param excelfilePath Excel文件路径 * @param startRow 开始行 * @param startCol 开始列 * @return List<ArrayList<String>> * @throws IOException * @throws BiffException */ public List<ArrayList<String>> readExcel(String excelfilePath, int startRow, int startCol) throws IOException, BiffException { // 读取xls文件 InputStream ins = new FileInputStream(excelfilePath); // 设置读文件编码 WorkbookSettings setEncode = new WorkbookSettings(); setEncode.setEncoding("UTF-8"); Workbook rwb = Workbook.getWorkbook(ins, setEncode); List<ArrayList<String>> alldata = new ArrayList<ArrayList<String>>(); ArrayList<String> data = null; alldata.clear(); // 获得当前Excel表共有几个sheet // Sheet[] sheets = rwb.getSheets(); // 获得表数 // int pages = sheets.length; // 将excel表中的数据读取出来 // 在从Excel中读取数据的时候不需要知道每个sheet有几行,有那多少列 // for (int i = 0; i < pages; i++) { Sheet sheet = rwb.getSheet(0); int cols = sheet.getColumns(); // 列 // 读取每一行对应的列数目 // 循环读取每一行的全部列数目的内容 int rows = sheet.getRows(); // 行 for (int r = startRow; r < rows; r++) { data = new ArrayList<String>(); // 行循环,Excel的行列是从(0,0)开始 for (int c = startCol; c < cols; c++) { Cell excelRows = sheet.getCell(c, r); String strRow = excelRows.getContents(); data.add(strRow); } alldata.add(data); } // } ins.close(); return alldata; } 自己写的java读取excel表格数据的方法,需要导入jxl包
㈥ 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 ExcelHandle {public static void main(String[] args) throws Exception {File file = new File("sss.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));// 打开HSSFWorkbookPOIFSFileSystem 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); 3.2已经自动Unicode处理了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);}}给你个例子代码,应该能帮到你!
㈦ java如何读取整个excel文件的内容
在Java中读取Excel文件的内容
在这里,我使用的是一个叫Java Excel API的东西,类似的还有jakarta的POI,不过感觉那个
太复杂了点儿。而且jxl对中文的支持相当的好,至少我在用的过程中一点问题没出。
一、下载地址
http://www.andykhan.com/jexcelapi/
二、特性
可以读取Excel 95, 97, 2000文件
可以读或写Excel 97及其以后版本的的公式(不过我发现好像有bug)
生成Excel 97格式的电子表格
支持字体、数字和日期格式化
支持单元格的颜色和阴影
可以编辑现有的文件
三、读文件
//声明一下,记得后面要关闭哦。。
Workbook workbook = null;
try {
workbook = Workbook.getWorkbook(new File("d:\temp\TestRead.xls"));
} catch (Exception e) {
throw new Exception("file to import not found!");
}
Sheet sheet = workbook.getSheet(0);
Cell cell = null;
int columnCount=3;
int rowCount=sheet.getRows();
for (int i = 0; i<rowcount; p="" {
for (int j = 0; j<columncount; p="" {
//注意,这里的两个参数,第一个是表示列的,第二才表示行
cell=sheet.getCell(j, i);
//要根据单元格的类型分别做处理,否则格式化过的内容可能会不正确
if(cell.getType()==CellType.NUMBER){
System.out.print(((NumberCell)cell).getValue());
}
else if(cell.getType()==CellType.DATE){
System.out.print(((DateCell)cell).getDate());
}
else{
System.out.print(cell.getContents());
}
//System.out.print(cell.getContents());
System.out.print("");
}
System.out.print("");
}
//关闭它,否则会有内存泄露
workbook.close();
㈧ 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)。
未经允许不得转载:山九号 » java打开excel文件|java怎么读取上传的excel文件