HSSFWorkbook 读写 Excel

首先导入Jar包,百度就能够下载到


写入操作:

HSSFWorkbook work = new HSSFWorkbook();
		HSSFSheet sheet = work.createSheet("book01");
		HSSFRow row = sheet.createRow(0);
		HSSFCell cell = row.createCell(0);
		cell.setCellValue("0:0 的值");
		
		work.write(new FileOutputStream(new File("D:\\officeOperation\\MyExcel.xls")));
		System.out.println("OK"); 

读写操作 (一种读全部,一种读的行和列):

读Excel所有内容,输出格式自动已经转换:

 HSSFWorkbook book = new HSSFWorkbook(
				 new FileInputStream(new File("D:\\officeOperation\\Students.xls")));
		ExcelExtractor excel = new ExcelExtractor(book);
		excel.setIncludeSheetNames(true);
		System.out.println(excel.getText());
细读:
 HSSFWorkbook book = new HSSFWorkbook(
				 new FileInputStream(new File("D:\\officeOperation\\Students.xls")));
		 //获取所有表的总数
		 int sheetNum =  book.getNumberOfSheets();
		 
		 for(int i=0;i<sheetNum;i++) {
			 //获取当前sheet
			 HSSFSheet  sheet = book.getSheetAt(i);
			 //获取表中的第一行
			 int firstRow = sheet.getFirstRowNum();
			 //获取表中的最后一行(必须是数据)
			 int lastRow = sheet.getLastRowNum();
			 
			 for(int rowNum=firstRow;rowNum<=lastRow;rowNum++) {
				Row row =  sheet.getRow(rowNum);
				if(row==null) {
					continue;
				}
				//获取数据第row行的第一列
				int firstCell = row.getFirstCellNum();
				//获取数据第row行的最后一列
				int lastCell = row.getLastCellNum();
				
				for(int colum=firstCell;colum<=lastCell;colum++) {
					Cell cell = row.getCell(colum);
					if(cell==null) {
						continue;
					}
					//字符串类型比较
					if(cell.getCellType()==Cell.CELL_TYPE_STRING) {
						System.out.print(cell.getStringCellValue()+"\t");
					}
					//Number类型比较
					if(cell.getCellType()==Cell.CELL_TYPE_NUMERIC) {
						System.out.print(cell.getNumericCellValue()+"\t");
					}
				}
				
				System.out.println();
			 }
		 } 

代码每天进步一点点

猜你喜欢

转载自blog.csdn.net/qq944484545/article/details/79888947