‘壹’ java POI读取Excel的时候怎么按列读取
按列读取的方法:
String pathname = "E:\\files\\title.xlsx";
File file = new File(pathname);
InputStream in = new FileInputStream(file);
//得到整个excel对象
XSSFWorkbook excel = new XSSFWorkbook(in);
//获取整个excel有多少个sheet
int sheets = excel.getNumberOfSheets();
//便利第一个sheet
Map<String,String> colMap = new HashMap<String, String>();
for(int i = 0 ; i < sheets ; i++ ){
XSSFSheet sheet = excel.getSheetAt(i);
if(sheet == null){
continue;
}
int mergedRegions = sheet.getNumMergedRegions();
XSSFRow row2 = sheet.getRow(0);
Map<Integer,String> category = new HashMap<Integer, String>();
for(int j = 0 ; j < mergedRegions; j++ ){
CellRangeAddress rangeAddress = sheet.getMergedRegion(j);
int firstRow = rangeAddress.getFirstColumn();
int lastRow = rangeAddress.getLastColumn();
category.put(rangeAddress.getFirstColumn(), rangeAddress.getLastColumn()+"-"+row2.getCell(firstRow).toString());
}
//便利每一行
for( int rowNum = 1 ; rowNum <= sheet.getLastRowNum() ; rowNum++ ){
System.out.println();
XSSFRow row = sheet.getRow(rowNum);
if(row == null){
continue;
}
short lastCellNum = row.getLastCellNum();
String cate = "";
Integer maxIndex = 0;
for( int col = row.getFirstCellNum() ; col < lastCellNum ; col++ ){
XSSFCell cell = row.getCell(col);
if(cell == null ){
continue;
}
if("".equals(cell.toString())){
continue;
}
int columnIndex = cell.getColumnIndex();
String string = category.get(columnIndex);
if(string != null && !string.equals("")){
String[] split = string.split("-");
cate = split[1];
maxIndex = Integer.parseInt(split[0]);
System.out.println(cate+"<-->"+cell.toString());
}else {
//如果当前便利的列编号小于等于合并单元格的结束,说明分类还是上面的分类名称
if(columnIndex<=maxIndex){
System.out.println(cate+"<-->"+cell.toString());
}else {
System.out.println("分类未知"+"<-->"+cell.toString());
}
}
}
}
}
}
‘贰’ 我想用java来读取Excel文件的某行某列,就是指定读取某个位置的数据,然后显示出来!怎么弄求
工念慧作中用到的导入excel一个方法,你还可以通过一些插件导入,代码要你自己了,基芦高辩本原理如下...
public Object importDoucument(MultipartFile uploadfile)
{
StringBuffer resultMessage = new StringBuffer();
ExcelImport excelImport = new ExcelImport();
Sheet sheet = null;
try
{
// 验证文件格式 如不出错 返回工作簿
excelImport.verifyExeclFile(uploadfile);
ExcelBean excelBean = excelImport.getExcelBean();
if (null != excelBean)
{
sheet = excelBean.getSheet();
}
//导入excel文件分析整理出list对象
List<StcCoreElements> dataList = getAssessCateRange(sheet, "战略要素名称", "战略要素名称"陪缺, 2, 1);
int num = 0;
if(dataList.size()>0){
for (StcCoreElements itemStcVO : dataList)
{
StcCoreElements stcCoreElementsVo = nitemStcVO
//*****修改些处
this.save(stcCoreElementsVo);
++num;
}
}
resultMessage.append("已成功导入 "+num+" 条核心要素信息");
}
catch (Exception e)
{
resultMessage.append(e.getMessage());
e.printStackTrace();
}
finally
{
excelImport.close();
}
return resultMessage;
}
private List<StcCoreElements> getAssessCateRange(Sheet sheet, String startName, String endName, int rowNum, int titleRowNum)
{
int[] cateRange = new int[2];
List<StcCoreElements> dataList = new ArrayList<StcCoreElements>();
int lastRowNumber = sheet.getLastRowNum();
Row cateRow = sheet.getRow(rowNum - 1);
Cell cateCell = cateRow.getCell(0);
String cateCellValue = ImportExcelUtil.getCellValue(cateCell, sheet);
if (StringUtils.isNotBlank(cateCellValue))
{
if (StringUtils.startsWith(cateCellValue, startName))
{
cateRange[0] = rowNum + titleRowNum;
}
}
String currentCellValue0 = "";
do
{
Row currentRow = sheet.getRow(rowNum);
StcCoreElements info =new StcCoreElements();
Cell currentCell0 = currentRow.getCell(0);
currentCellValue0 = ImportExcelUtil.getCellValue(currentCell0, sheet);
info.setOverallPlan(currentCellValue0);
dataList.add(info);
rowNum++;
} while (rowNum <= lastRowNumber);
return dataList;
}
‘叁’ java如何读取整个excel文件的内容
工具:
参考代码及注释如下:
import Java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; public class ReadExcel { public static void readExcel(File file){ try { InputStream inputStream = new FileInputStream(file); String fileName = file.getName(); Workbook wb = null; // poi-3.9.jar 只可以读取2007以下的版本,后缀为:xsl wb = new HSSFWorkbook(inputStream);//解析xls格式 Sheet sheet = wb.getSheetAt(0);//第一个工作表 ,第二个则为1,以此类推... int firstRowIndex = sheet.getFirstRowNum(); int lastRowIndex = sheet.getLastRowNum(); for(int rIndex = firstRowIndex; rIndex <= lastRowIndex; rIndex ++){ Row row = sheet.getRow(rIndex); if(row != null){ int firstCellIndex = row.getFirstCellNum(); // int lastCellIndex = row.getLastCellNum(); //此处参数cIndex决定可以取到excel的列数。 for(int cIndex = firstCellIndex; cIndex < 3; cIndex ++){ Cell cell = row.getCell(cIndex); String value = ""; if(cell != null){ value = cell.toString(); System.out.print(value+"\t"); } } System.out.println(); } } } catch (FileNotFoundException e) { // TODO 自动生成 catch 块 e.printStackTrace(); } catch (IOException e) { // TODO 自动生成 catch 块 e.printStackTrace(); } } public static void main(String[] args) { File file = new File("D:/test.xls"); readExcel(file); }}
‘肆’ Java POI读取Excel的时候怎么按列读取
按列读取的方法:
String pathname = "E:\\files\\title.xlsx";
File file = new File(pathname);
InputStream in = new FileInputStream(file);
//得到整个雀陵excel对象
XSSFWorkbook excel = new XSSFWorkbook(in);
//获取整个excel有多少个sheet
int sheets = excel.getNumberOfSheets();
//便利拍岁态第一个sheet
Map<String,String> colMap = new HashMap<String, String>();
for(int i = 0 ; i < sheets ; i++ ){
XSSFSheet sheet = excel.getSheetAt(i);
if(sheet == null){
continue;
}
int mergedRegions = sheet.getNumMergedRegions();
XSSFRow row2 = sheet.getRow(0);
Map<Integer,String> category = new HashMap<Integer, String>();
for(int j = 0 ; j < mergedRegions; j++ ){
CellRangeAddress rangeAddress = sheet.getMergedRegion(j);
int firstRow = rangeAddress.getFirstColumn();
int lastRow = rangeAddress.getLastColumn();
category.put(rangeAddress.getFirstColumn(), rangeAddress.getLastColumn()+"-"+row2.getCell(firstRow).toString());
}
//便利每一行
for( int rowNum = 1 ; rowNum <= sheet.getLastRowNum() ; rowNum++ ){
System.out.println();
XSSFRow row = sheet.getRow(rowNum);
if(row == null){
continue;
}
short lastCellNum = row.getLastCellNum();
String cate = "袭源";
Integer maxIndex = 0;
for( int col = row.getFirstCellNum() ; col < lastCellNum ; col++ ){
XSSFCell cell = row.getCell(col);
if(cell == null ){
continue;
}
if("".equals(cell.toString())){
continue;
}
int columnIndex = cell.getColumnIndex();
String string = category.get(columnIndex);
if(string != null && !string.equals("")){
String[] split = string.split("-");
cate = split[1];
maxIndex = Integer.parseInt(split[0]);
System.out.println(cate+"<-->"+cell.toString());
}else {
//如果当前便利的列编号小于等于合并单元格的结束,说明分类还是上面的分类名称
if(columnIndex<=maxIndex){
System.out.println(cate+"<-->"+cell.toString());
}else {
System.out.println("分类未知"+"<-->"+cell.toString());
}
}
}
}
}
}
‘伍’ 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;
}
}
‘陆’ 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);
}
}
‘柒’ java 如何一列一列读取excel数据。网上好多资料只是读取前两三行的例子,我的是读取一个列下所有的行内容
1、一般java读取excel数据都是按行读取,网上的资料都是例子数则,谁也不会拿个几千行的excel文件做测试;
2、既然你的文件只有一列,即使是按行读取也没有任何问题,只要按行读取,薯毁棚每行只取你需要的那一列就行了,非常的简单。
3、主要不是列的问题,余核是你根本不会java读取excel文件,网上那么多的例子也没看懂。
‘捌’ java 如何一列一列读取excel数据
工作用导入excel通些插件导入代码罩族要自基本原理...
public Object importDoucument(MultipartFile uploadfile)
{
StringBuffer resultMessage = new StringBuffer();
ExcelImport excelImport = new ExcelImport();
Sheet sheet = null;
try
{
// 验证友漏文件格式 错 返工作簿
excelImport.verifyExeclFile(uploadfile);
ExcelBean excelBean = excelImport.getExcelBean();
if (null != excelBean)
{
sheet = excelBean.getSheet();
}
//导入excel文件析整理list象
List dataList = getAssessCateRange(sheet, "战略要素名称", "战略要素名称", 2, 1);
int num = 0;
if(dataList.size()>0){
for (StcCoreElements itemStcVO : dataList)
{
StcCoreElements stcCoreElementsVo = nitemStcVO
//*****修改些处
this.save(stcCoreElementsVo);
++num;
}
}
resultMessage.append("已功导入 "+num+"好闷烂 条核要素信息");
}
catch (Exception e)
{
resultMessage.append(e.getMessage());
e.printStackTrace();
}
finally
{
excelImport.close();
}
return resultMessage;
}
private List getAssessCateRange(Sheet sheet, String startName, String endName, int rowNum, int titleRowNum)
{
int[] cateRange = new int[2];
List dataList = new ArrayList();
int lastRowNumber = sheet.getLastRowNum();
Row cateRow = sheet.getRow(rowNum - 1);
Cell cateCell = cateRow.getCell(0);
String cateCellValue = ImportExcelUtil.getCellValue(cateCell, sheet);
if (StringUtils.isNotBlank(cateCellValue))
{
if (StringUtils.startsWith(cateCellValue, startName))
{
cateRange[0] = rowNum + titleRowNum;
}
}
String currentCellValue0 = "";
do
{
Row currentRow = sheet.getRow(rowNum);
StcCoreElements info =new StcCoreElements();
Cell currentCell0 = currentRow.getCell(0);
currentCellValue0 = ImportExcelUtil.getCellValue(currentCell0, sheet);
info.setOverallPlan(currentCellValue0);
dataList.add(info);
rowNum++;
} while (rowNum <= lastRowNumber);
return dataList;
}
‘玖’ 怎么获取excel字符间列java
一、excel读取的两种方式
Java中解析excel的方式,我目前知道的有两种,一种是 jxl 读取,另一种是 poi 读取
1.1 jxl 和 poi 的区缺旦亏别和选择
① jxl 只能解析 xls 文件,不能 解析 xlsx 文件; poi 则是可伏神以同时兼容xls 和xlsx两种文件类型,这是要注意的第一个点;
② 这迟改两个方法的读取方式不一样,jxl 读取的是 先读列 然后循环获取的该列每行的信息。poi 读取是 先读行,再循环获取每列的信息。如下图:
‘拾’ 浅谈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);