Ⅰ java读取EXCEL文件
相关功能代码比较多 贴出来不是很方便 我跟你说一下思路吧首先是用到的工具是poi 这个你可以去官网载一个其次 你要注意区分你的excel 是旧的还是新的 office 07版之前和07版之后的 读取的类不一样把握住这2点 差不多就OK了大体的读取流程是读取workbook -> sheet -> row -> col
Ⅱ Java中如何读取excel文件内容并且将内容以表格的形式显示在窗体里
这个设计的内容如下:
PoI技术,将表格数据解析存储到数据库
数据显示,jqGrid这些专业的图表数据显示插件可以完成,当然也可以在JSP页面用普通的<table>标签实现
Ⅲ 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文件里面的数据
使用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);}}
Ⅳ 浅谈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);
Ⅵ java如何读取整个excel文件的内容
在Java中读取Excel文件的内容
在这里,我使用的是一个叫Java Excel API的东西,类似的还有的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文件数据,保存到数据库中
public String[][] readExcel(String filePath) { String[][] s = null; try { HSSFWorkbook workbook = new HSSFWorkbook(new FileInputStream( filePath)); HSSFSheet sheet = workbook.getSheetAt(0); int rows = sheet.getPhysicalNumberOfRows(); s = new String[rows][]; if (rows > 0) { // 获取总列数` int cells = sheet.getRow(0).getPhysicalNumberOfCells(); for (int r =0; r < rows; r++) { HSSFRow row = sheet.getRow(r); String[] cellsvalue = new String[cells+1]; for (short c = 0; c < cells; c++) { String value = ""; HSSFCell cell = row.getCell(c); if (cell != null) { switch (cell.getCellType()) { case HSSFCell.CELL_TYPE_FORMULA: // break; case HSSFCell.CELL_TYPE_NUMERIC: if (HSSFDateUtil.isCellDateFormatted(cell)) { value = new java.text.SimpleDateFormat( "yyyy-MM-dd").format(cell .getDateCellValue()); } else { value = String.valueOf(cell .getNumericCellValue()); } break; case HSSFCell.CELL_TYPE_STRING: value = cell.getStringCellValue(); break; case HSSFCell.CELL_TYPE_BLANK: value=""; default: break; } if (cell == null) { value=""; } } cellsvalue[c] = value; if(value.endsWith(".0")){ cellsvalue[c] = value.substring(0, value.length()-2); } } s[r] = cellsvalue; java.io.File myfile = new java.io.File(filePath); if (myfile.exists()) { myfile.delete(); } } } } catch (Exception ex) { // TODO 自动生成 catch 块 ex.printStackTrace(); } return s; }
Ⅷ 用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自动读取web项目中的excel文件
package com.bjhz.gcp.common.util;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.OutputStream;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;import java.sql.Timestamp;import java.text.SimpleDateFormat;import java.util.ArrayList;import java.util.Date;import java.util.HashMap;import java.util.List;import java.util.Locale;import java.util.Map;import org.apache.poi.hssf.usermodel.HSSFCell;import org.apache.poi.hssf.usermodel.HSSFCellStyle;import org.apache.poi.hssf.usermodel.HSSFFont;import org.apache.poi.hssf.usermodel.HSSFRichTextString;import org.apache.poi.hssf.usermodel.HSSFRow;import org.apache.poi.hssf.usermodel.HSSFSheet;import org.apache.poi.hssf.usermodel.HSSFWorkbook;/** * * 导出EXCEL * @author Herenqing * */public class WritExcel { public static final Integer WRIT_TITLE = 1; public static final Integer NO_WRIT_TITLE = 0; private static String format = "yyyy-MM-dd HH:mm:ss"; private static String nullDisplay = ""; private List<String> columnName = new ArrayList<String>(); private Map<String, String> columnObject = new HashMap<String, String>(); private String savePath; private OutputStream outputStream;/** * 构造写入EXCEL的路径 * 使用 put 方法创建导出的内容 * 使用 writ 方法将对象写入EXCEL * @param savePath * @throws FileNotFoundException */ public WritExcel(String savePath) { this.savePath = savePath; } /** * 构造写入EXCEL的路径 * 使用 put 方法创建导出的内容 * 使用 writOutputStream 方法将对象写入 HSSFWorkbook * @param savePath * @throws FileNotFoundException */ /*public WritExcel() { }*/ /** * 构建导出顺序及导出字段 * @param key 导出字段名 * @param value 表头 */ public void put(String key,String value) { this.columnName.add(key); this.columnObject.put(key, value); } /** * 写入EXCEL * @param <T> 写入EXCEL的对象类型 * @param objects 写入EXCEL的对象 * @param model 写不写表头 * @throws IOException * @throws InvocationTargetException * @throws IllegalAccessException * @throws IllegalArgumentException */ public <T> void writ(List<T> objects,Integer model) throws IOException, IllegalArgumentException, IllegalAccessException, InvocationTargetException { // 创建一个Excel HSSFWorkbook book = new HSSFWorkbook(); // 创建一个工作簿 HSSFSheet sheet = book.createSheet(); // 设置工作簿的默认列宽 sheet.setDefaultColumnWidth(30); Integer start = 0; if (model == WRIT_TITLE) { HSSFCellStyle titleStyle = buildTitleStyle(book); writExcelTitle(sheet,titleStyle); start = WRIT_TITLE; } HSSFCellStyle columnStyle = buildColumnStyle(book); writExcelColumn(objects,start,sheet,columnStyle); outputStream = new FileOutputStream(savePath); book.write(outputStream); outputStream.close(); } /** * 写入EXCEL * @param <T> 写入EXCEL的对象类型 * @param objects 写入EXCEL的对象 * @param model 写不写表头 * @throws IOException * @throws InvocationTargetException * @throws IllegalAccessException * @throws IllegalArgumentException */ /*public <T> HSSFWorkbook writOutputStream(List<T> objects,Integer model) throws IOException, IllegalArgumentException, IllegalAccessException, InvocationTargetException { // 创建一个Excel HSSFWorkbook book = new HSSFWorkbook(); // 创建一个工作簿 HSSFSheet sheet = book.createSheet(); // 设置工作簿的默认列宽 sheet.setDefaultColumnWidth((short)30); Integer start = 0; if (model == WRIT_TITLE) { HSSFCellStyle titleStyle = buildTitleStyle(book); writExcelTitle(sheet,titleStyle); start = WRIT_TITLE; } HSSFCellStyle columnStyle = buildColumnStyle(book); writExcelColumn(objects,start,sheet,columnStyle); return book; }*/ /** * 使用内容样式 * @return */ private HSSFCellStyle buildColumnStyle(HSSFWorkbook book){ // 设置样式 HSSFCellStyle columnStyle = book.createCellStyle(); //titleStyle.setFillForegroundColor(HSSFColor.SKY_BLUE.index); //titleStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); //titleStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN); columnStyle.setLeftBorderColor(HSSFCellStyle.BORDER_THIN); columnStyle.setRightBorderColor(HSSFCellStyle.BORDER_THIN); columnStyle.setTopBorderColor(HSSFCellStyle.BORDER_THIN); columnStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 设置字体 HSSFFont font = book.createFont(); //font.setColor(HSSFColor.VIOLET.index); //font.setFontHeight((short)12); //font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); // 把字体应用到当前样式 columnStyle.setFont(font); return columnStyle; }/** * 使用表头样式 */ private HSSFCellStyle buildTitleStyle(HSSFWorkbook book){ // 设置样式 HSSFCellStyle titleStyle = book.createCellStyle(); //titleStyle.setFillForegroundColor(HSSFColor.SKY_BLUE.index); //titleStyle.setFillPattern(HSSFCellStyle.SOLID_FOREGROUND); //titleStyle.setBorderBottom(HSSFCellStyle.BORDER_THIN); titleStyle.setLeftBorderColor(HSSFCellStyle.BORDER_THIN); titleStyle.setRightBorderColor(HSSFCellStyle.BORDER_THIN); titleStyle.setTopBorderColor(HSSFCellStyle.BORDER_THIN); titleStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 设置字体 HSSFFont font = book.createFont(); //font.setColor(HSSFColor.VIOLET.index); //font.setFontHeight((short)12); font.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD); // 把字体应用到当前样式 titleStyle.setFont(font); return titleStyle; } /** * 写入表头 */ private void writExcelTitle(HSSFSheet sheet,HSSFCellStyle titleStyle) throws IOException { // 表头 HSSFRow title = sheet.createRow(0); for (Integer i = 0; i < columnName.size(); i++) { HSSFCell cell = title.createCell(i); cell.setCellStyle(titleStyle); HSSFRichTextString value = new HSSFRichTextString(columnObject.get(columnName.get(i))); cell.setCellValue(value); } } /** * 写入内容 * @throws InvocationTargetException * @throws IllegalAccessException * @throws IllegalArgumentException */ private <T> void writExcelColumn(List<T> objects,Integer start,HSSFSheet sheet,HSSFCellStyle titleStyle) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException{ for (int i = 0; i < objects.size(); i++) { Object object = objects.get(i); Class<?> cls = object.getClass(); HSSFRow column = sheet.createRow(start); for (int j = 0; j < columnName.size(); j++) { try { Method method = cls.getMethod(getMethod(columnName.get(j))); Object invokeResult = method.invoke(object); String result = returnTypeResult(invokeResult); HSSFCell cell = column.createCell(j); cell.setCellStyle(titleStyle); HSSFRichTextString value = new HSSFRichTextString(result); cell.setCellValue(value); } catch (NoSuchMethodException e) { continue; } } start++; } } /** * 构建get方法 */ private static String getMethod(String fieldName){ return "get"+fieldName.substring(0,1).toUpperCase(Locale.CHINA)+fieldName.substring(1); }private static String returnTypeResult(Object object){ if (object == null) { return nullDisplay; } if (object.getClass().getName().equals("java.util.Date")) { return formatDate(object); }else if (object.getClass().getName().equals("java.sql.Timestamp")) { Timestamp timestamp = Timestamp.valueOf(object.toString()); Date date = timestamp; return formatDate(date); }else { return object.toString(); } } /** * formatDate */ private static String formatDate(Object date) { return new SimpleDateFormat(format).format(date); }}
Ⅹ 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文件的内容