package com.Exp;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
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;
import java.io.FileOutputStream;
public class T1 {
//读取XLS
public static void ReEx(String excelPath) throws IOException{
String encoding = "GBK";
File excel = new File(excelPath);
if (excel.isFile() && excel.exists()) { //判断文件是否存在
String[] split = excel.getName().split("\\."); //.是特殊字符,需要转义!!!!!
Workbook wb;
//根据文件后缀(xls/xlsx)进行判断
if ( "xls".equals(split[1])){
FileInputStream fis = new FileInputStream(excel); //文件流对象
wb = new HSSFWorkbook(fis);
}
else {
System.out.println("文件类型错误!");
return;
}
//开始解析
Sheet sheet = wb.getSheetAt(0); //读取sheet 0
int firstRowIndex = sheet.getFirstRowNum(); //第一行是列名,所以不读
int lastRowIndex = sheet.getLastRowNum();
System.out.println("firstRowIndex: "+firstRowIndex);
System.out.println("lastRowIndex: "+lastRowIndex);
for(int rIndex = firstRowIndex; rIndex <= lastRowIndex; rIndex++) { //遍历行
System.out.println("rIndex: " + rIndex);
Row row = sheet.getRow(rIndex);
if (row != null) {
int firstCellIndex = row.getFirstCellNum();
int lastCellIndex = row.getLastCellNum();
for (int cIndex = firstCellIndex; cIndex < lastCellIndex; cIndex++) { //遍历列
Cell cell = row.getCell(cIndex);
if (cell != null) {
System.out.println(cell.toString());
}
}
}
}
} else {
System.out.println("找不到指定的文件");
}
}
/**写XLS
*
*
* */
public static void testWrite(String url){
//创建工作簿
Workbook wb = new HSSFWorkbook();
//创建 Sheet页
Sheet sheetA = wb.createSheet("A");
for(int i=0; i<9; i++){
//创建单元行
Row row = sheetA.createRow(i);
for(int j=0; j<=i; j++){
Cell cell = row.createCell(j);
cell.setCellValue((j+1)+" * "+(i+1)+" = " + (j+1)*(i+1));
}
}
try {
//路径需要存在
FileOutputStream fos = new FileOutputStream("E:\\t1.xls");
wb.write(fos);
fos.close();
wb.close();
System.out.println("写数据结束!");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException {
String path="E:\\t1.xls";
ReEx(path);//xls文件读取
testWrite(path);//写xls
}
}