依賴請參考版本一
先說寫入標題欄 java代碼
public class PoiColumnTest {
public static void main(String[] args) throws Exception{
// 準備數據
List<String> titles = Arrays.asList("編號","姓名","圖片","法號","狀態");
// 1.創建工作簿對象
HSSFWorkbook workbook = new HSSFWorkbook();
// 2.創建工作表
HSSFSheet sheet = workbook.createSheet("guru");
// 3.創建一行
HSSFRow titleRow = sheet.createRow(0);
for (int i = 0; i < titles.size(); i++) {
// 4.創建單元格
HSSFCell cell = titleRow.createCell(i);
// 5.寫入數據
String s = titles.get(i);
cell.setCellValue(s);
}
// 6.輸出到本地
workbook.write(new FileOutputStream(new File("E://guru.xls")));
}
}
效果
再說數據庫中數據進行導出的java代碼
@SpringBootTest(classes = {ShujiegouApplication.class})
@RunWith(SpringJUnit4ClassRunner.class)
public class PoiTestDataBase {
@Autowired
private SysColumnService sysColumnService;
// @Autowired
// private SysColumnMapper sysColumnMapper;
@Test
public void test1() throws Exception{
/**
* 獲取數據庫中的數據 填充在Excel表格中
* @throws Exception
*/
// 準備數據
List<String> titles = Arrays.asList("欄目Id","欄目名稱","欄目父id值","菜單級別","跳轉頁面");
// 數據查詢 上師全部的數據
List<SysColumn> sysColumnAll = sysColumnService.getSysColumnAll();
// List<SysColumn> sysColumnAll = sysColumnMapper.selectAll();
// 1. 新建一個HSSFWorkbook 對象
HSSFWorkbook workbook = new HSSFWorkbook();
// 單元格樣式對象 設置樣式
HSSFCellStyle cellStyle = workbook.createCellStyle();
HSSFFont font = workbook.createFont();
font.setColor((short)10);
font.setFontName("宋體");
cellStyle.setFont(font);
// 2. 新建一個HSSFSheet對象
HSSFSheet sheet = workbook.createSheet("guru");
// 3. 寫入標題欄數據
// 創建行
HSSFRow titleRow = sheet.createRow(0);
for (int i = 0; i < titles.size(); i++) {
// 創建單元格
HSSFCell titleCell = titleRow.createCell(i);
// 添加樣式
titleCell.setCellStyle(cellStyle);
// 寫入數據
titleCell.setCellValue(titles.get(i));
}
// 4. 寫入上師數據
for (int i = 0; i < sysColumnAll.size(); i++) {
SysColumn sysColumn = sysColumnAll.get(i);
// 創建行
HSSFRow row = sheet.createRow(i + 1);
// 創建單元格
HSSFCell cell0 = row.createCell(0);
cell0.setCellValue(sysColumn.getId());
HSSFCell cell1 = row.createCell(1);
cell1.setCellValue(sysColumn.getColumnName());
HSSFCell cell2 = row.createCell(2);
cell2.setCellValue(sysColumn.getParentId());
HSSFCell cell3 = row.createCell(3);
cell3.setCellValue(sysColumn.getColumnRank());
HSSFCell cell4 = row.createCell(4);
cell4.setCellValue(sysColumn.getEnName());
}
// 5. 輸出
workbook.write(new FileOutputStream(new File("E://guruall.xls")));
}
}
效果