java用jxl处理excel,包含读取和写入
时间: 2023-07-16 21:14:28 浏览: 157
JXL是Java Excel API的缩写,可以处理Excel文件的读取和写入。以下是使用JXL进行Excel文件读取和写入的示例代码:
1. 读取Excel文件:
```java
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
public class ExcelReader {
public static void main(String[] args) {
try {
File file = new File("test.xls");
Workbook workbook = Workbook.getWorkbook(file);
Sheet sheet = workbook.getSheet(0);
int rowCount = sheet.getRows();
List<String[]> list = new ArrayList<String[]>();
for (int i = 0; i < rowCount; i++) {
Cell[] cells = sheet.getRow(i);
String[] row = new String[cells.length];
for (int j = 0; j < cells.length; j++) {
row[j] = cells[j].getContents();
}
list.add(row);
}
for (String[] row : list) {
for (String cell : row) {
System.out.print(cell + "\t");
}
System.out.println();
}
workbook.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
2. 写入Excel文件:
```java
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
public class ExcelWriter {
public static void main(String[] args) {
try {
File file = new File("test.xls");
WritableWorkbook workbook = Workbook.createWorkbook(file);
WritableSheet sheet = workbook.createSheet("Sheet1", 0);
List<String[]> list = new ArrayList<String[]>();
list.add(new String[] {"Name", "Age", "Gender"});
list.add(new String[] {"Tom", "20", "Male"});
list.add(new String[] {"Lucy", "18", "Female"});
for (int i = 0; i < list.size(); i++) {
String[] row = list.get(i);
for (int j = 0; j < row.length; j++) {
Label label = new Label(j, i, row[j]);
sheet.addCell(label);
}
}
workbook.write();
workbook.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
以上代码演示了如何使用JXL处理Excel文件的读取和写入,通过这些示例代码,你可以根据自己的需要进行调整和扩展。
阅读全文