工做中经常须要将查询或者计算的结果导出到excel中,方便统计和查看,或者从excel中读取内容。除了原来使用的poi,还有一种轻量高效的方法就是使用jxl,下面看看jxl的使用。java
<!-- 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(); } }