Java语言写一个读取本地excel表中的数据并调用已经写好的接口
时间: 2024-05-06 18:20:00 浏览: 108
首先需要使用一个Java库来读取Excel表格,比较常用的有Apache POI和JExcelAPI,这里以Apache POI为例。
1. 首先需要添加Apache POI的依赖,可以在pom.xml文件中添加以下代码:
```xml
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>
```
2. 读取Excel表格需要创建一个Workbook对象,可以使用以下代码:
```java
FileInputStream file = new FileInputStream(new File("path/to/excel/file.xlsx"));
Workbook workbook = new XSSFWorkbook(file); // 指定xlsx格式的文件
```
3. 获取表格中的数据需要根据具体的行和列获取,可以使用以下代码:
```java
Sheet sheet = workbook.getSheetAt(0); // 获取第一个工作表
Row row = sheet.getRow(rowIndex); // 获取指定行
Cell cell = row.getCell(columnIndex); // 获取指定列
String value = cell.getStringCellValue(); // 获取单元格的值
```
4. 调用已经写好的接口需要使用Java的HttpURLConnection类,可以使用以下代码:
```java
URL url = new URL("http://localhost:8080/api");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setDoOutput(true);
String requestBody = "{\"data\":\"" + value + "\"}";
OutputStream outputStream = connection.getOutputStream();
outputStream.write(requestBody.getBytes());
outputStream.flush();
outputStream.close();
```
其中,将Excel表格中获取到的数据放入到requestBody中,作为接口请求的参数。最后需要关闭连接。
完整的代码示例:
```java
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
public class ExcelReader {
public static void main(String[] args) throws IOException {
FileInputStream file = new FileInputStream(new File("path/to/excel/file.xlsx"));
Workbook workbook = new XSSFWorkbook(file);
Sheet sheet = workbook.getSheetAt(0);
for (Row row : sheet) {
Cell cell = row.getCell(0);
String value = cell.getStringCellValue();
URL url = new URL("http://localhost:8080/api");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("POST");
connection.setRequestProperty("Content-Type", "application/json");
connection.setDoOutput(true);
String requestBody = "{\"data\":\"" + value + "\"}";
OutputStream outputStream = connection.getOutputStream();
outputStream.write(requestBody.getBytes());
outputStream.flush();
outputStream.close();
connection.disconnect();
}
}
}
```
阅读全文
相关推荐


















