1代码
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.*;
public class POIUtil {
/**
* 读取一列,拼接成一个字符串
* @param filePath 文件路径 xls格式的
* @param col 第几列,从零开始
* @throws IOException
*/
public static void readColumn(String filePath,int col) throws IOException {
String nameList="";
// 获取Excel文件
File excelFile = new File(filePath);
// 获取Excel工作簿
InputStream inputStream = new FileInputStream(excelFile);
Workbook workbook = new HSSFWorkbook(inputStream);
Sheet sheet=workbook.getSheetAt(0);
int rowEnd = sheet.getPhysicalNumberOfRows();
for (int i = 0; i <rowEnd ; i++) {
Row row=sheet.getRow(i);
Cell cell=row.getCell(col);
String value= cell.getStringCellValue();
nameList+=value+"、";
}
System.out.println(nameList);
workbook.close();
}
/**
* 向excel中写
* @param filePath 模板文件路径
* @param outPath 输出文件路径
* @throws Exception
*/
public static void write(String filePath,String outPath) throws Exception{
// 获取Excel文件
File excelFile = new File(filePath);
// 获取Excel工作簿
InputStream inputStream = new FileInputStream(excelFile);
Workbook workbook = new HSSFWorkbook(inputStream);
Sheet sheet0 = workbook.getSheetAt(0);
Row row=sheet0.createRow(0);
Cell cell=row.createCell(0);
cell.setCellValue("你好");
FileOutputStream fileOut = new FileOutputStream(outPath);
workbook.write(fileOut);
fileOut.close();
workbook.close();
}
}
2依赖
<dependencies>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.17</version>
</dependency>
</dependencies>