标签:void tco lap ima getc book ++ info table
工作中常常需要将查询或者计算的结果导出到excel中,方便统计和查看,或者从excel中读取内容。除了原来使用的poi,还有一种轻量高效的方法就是使用jxl,下面看看jxl的使用。<!-- https://mvnrepository.com/artifact/jexcelapi/jxl -->
<dependency>
<groupId>jexcelapi</groupId>
<artifactId>jxl</artifactId>
<version>2.6</version>
</dependency>
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import java.io.File;
public class TestJxl {
public static void main(String[] args) throws Exception{
//写excel
writeExcel();
//读excel
//readExcel();
}
/**
* 写数据到excel中
*
* @throws Exception
*/
private static void writeExcel() throws Exception {
File xlsFile = new File("test.xls");
// 创建一个工作簿
WritableWorkbook workbook = Workbook.createWorkbook(xlsFile);
// 创建一个工作表
WritableSheet sheet = workbook.createSheet("sheet1", 0);
// 向行和列中写数据
for (int row = 0; row < 10; row++) {
for (int col = 0; col < 10; col++) {
// 向工作表中添加数据
sheet.addCell(new Label(col, row, "data[" + row + ":" + col + "]"));
}
}
//关闭资源
workbook.write();
workbook.close();
}
/**
* 从excel中读取数据
* @throws Exception
*/
private static void readExcel() throws Exception {
File xlsFile = new File("test.xls");
// 获得工作簿对象
Workbook workbook = Workbook.getWorkbook(xlsFile);
// 获得所有工作表
Sheet[] sheets = workbook.getSheets();
// 遍历工作表
if (sheets != null) {
for (Sheet sheet : sheets) {
// 获得行数
int rows = sheet.getRows();
// 获得列数
int cols = sheet.getColumns();
// 读取数据
for (int row = 0; row < rows; row++) {
for (int col = 0; col < cols; col++) {
Cell cell = sheet.getCell(col, row);
System.out.print(cell.getContents() + " ");
}
System.out.println();
}
}
}
//关闭资源
workbook.close();
}
}
标签:void tco lap ima getc book ++ info table
原文地址:https://blog.51cto.com/simplelife/2445192