package com.aishidai.web.ceshi;
import com.aishidai.entitydto.Test;
import com.aishidai.manager.TestCe;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import java.io.File;
import java.util.List;
@Controller
public class PushMysqlToExcel {
@Autowired
TestCe testCe;
@RequestMapping(value ="queryexcel",method = {RequestMethod.GET,RequestMethod.POST})
@ResponseBody
public String query() {
JSONObject jsonObject = new JSONObject();
jsonObject.put("success",false);
try {
WritableWorkbook wwb = null;
// 创建可写入的Excel工作簿
String fileName = "D://book1.xls";
File file=new File(fileName);
if (!file.exists()) {
file.createNewFile();
}
//以fileName为文件名来创建一个Workbook
wwb = Workbook.createWorkbook(file);
// 创建工作表
WritableSheet ws = wwb.createSheet("Test Sheet1", 0);
//查询数据库中所有的数据
List<Test> list= testCe.queryAll();
//要插入到的Excel表格的行号,默认从0开始
//Label labelId= new Label(0, 0, "编号(id)");//表示第
Label labelName= new Label(0, 0, "姓名(name)");
Label labelSex= new Label(1, 0, "性别(sex)");
Label labelNum= new Label(2, 0, "薪水(num)");
//ws.addCell(labelId);
ws.addCell(labelName);
ws.addCell(labelSex);
ws.addCell(labelNum);
for (int i = 0; i < list.size(); i++) {
//Label labelId_i= new Label(0, i+1, list.get(i).getId()+"");
Label labelName_i= new Label(0, i+1, list.get(i).getName());
Label labelSex_i= new Label(1, i+1, list.get(i).getSex());
Label labelNum_i= new Label(2, i+1, list.get(i).getPhone()+"");
//ws.addCell(labelId_i);
ws.addCell(labelName_i);
ws.addCell(labelSex_i);
ws.addCell(labelNum_i);
}
//写进文档
wwb.write();
// 关闭Excel工作簿对象
wwb.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
jsonObject.put("success",true);
return jsonObject.toString();
}
}
依赖
<dependency>
<groupId>net.sourceforge.jexcelapi</groupId>
<artifactId>jxl</artifactId>
<version>2.6.12</version>
</dependency>
转载:
https://www.cnblogs.com/zyw-205520/p/3762954.html