日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 运维知识 > 数据库 >内容正文

数据库

使用POI技术简单的将数据库中的数据读取出为Excel文件

發布時間:2024/4/15 数据库 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 使用POI技术简单的将数据库中的数据读取出为Excel文件 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

利用POI生成.xlxs

效果圖


利用反射將實體類的屬性讀取出來,然后對應數據庫表中的字段,循環插入對應的數據

數據來源

本次測試的數據為數據庫查詢得出,所以需要MyBatis查詢數據庫,然后根據反射將實體類的屬性匹配字段的數據循環讀取出來,并寫入文件.

代碼詳解(POI寫和讀在代碼中的不同測試方法中)

package com.fs.testpoi;import com.fs.domain.store.Question; import com.fs.service.store.impl.QuestionServiceImpl; import org.apache.poi.ss.usermodel.*; import org.apache.poi.ss.util.CellRangeAddress; import org.apache.poi.xssf.usermodel.XSSFCell; import org.apache.poi.xssf.usermodel.XSSFRow; import org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.junit.Test;import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.lang.reflect.Field; import java.util.List;/*** 使用POI讀取數據庫生成為Excel表格文件*/ public class TestPOI {//需要調用業務層方法來查詢數據庫中所有數據private QuestionServiceImpl questionService = new QuestionServiceImpl();/*** 利用反射實現POI將數據寫入*/@Testpublic void POIToFS(){//poi寫excel//創建xlxs文件對象XSSFWorkbook workbook = new XSSFWorkbook();//創建工作表對象XSSFSheet sheet = workbook.createSheet("題目數據文件");/*** 整體流程* 相當于workbook對象--->sheet對象--->row對象--->cell對象--->設置樣式*//*通用樣式配置*///創建一個標題樣式CellStyle cellStyle_title_fields = workbook.createCellStyle();//設置水平對齊cellStyle_title_fields.setAlignment(HorizontalAlignment.CENTER);//設置上下左右的線條cellStyle_title_fields.setBorderTop(BorderStyle.HAIR);cellStyle_title_fields.setBorderBottom(BorderStyle.HAIR);cellStyle_title_fields.setBorderLeft(BorderStyle.HAIR);cellStyle_title_fields.setBorderRight(BorderStyle.HAIR);/*//制作標題*///合并單元格sheet.addMergedRegion(new CellRangeAddress(1, 1, 1, 13));//獲取第一行XSSFRow row_1 = sheet.createRow(1);//第一行的第一列XSSFCell cell_1_1 = row_1.createCell(1);//給這個格子里面設置值cell_1_1.setCellValue("在線試題導出信息");//創建一個標題樣式CellStyle cellStyle_title = workbook.createCellStyle();//設置水平對齊cellStyle_title.setAlignment(HorizontalAlignment.CENTER);//設置垂直對齊cellStyle_title.setVerticalAlignment(VerticalAlignment.CENTER);//給這標題設置樣式cell_1_1.setCellStyle(cellStyle_title);/*//制作表頭*///定義一個數組,來存儲表頭數據String[] fields = {"題目ID", "所屬公司ID", "所屬目錄ID", "題目簡介", "題干描述", "題干配圖", "題目分析", "題目類型", "題目難度", "是否經典題", "題目狀態", "審核狀態","創建時間"};//獲取第二行XSSFRow row_2 = sheet.createRow(2);for (int i = 0; i < fields.length; i++) {//第二行循環加入列XSSFCell cell_2_for = row_2.createCell(1 + i);//給這個格子里面設置值cell_2_for.setCellValue(fields[i]); // //創建一個標題樣式 // CellStyle cellStyle_title_fields = wb.createCellStyle(); // //設置水平對齊 // cellStyle_title_fields.setAlignment(HorizontalAlignment.CENTER);//給這標題設置樣式cell_2_for.setCellStyle(cellStyle_title_fields);}/*** 反射實現數據寫入* 每一個Question數據就是一行數據,Question的屬性就沒每個列*///調用業務層查詢出所有的Question數據List<Question> datas = questionService.findAll();for (int i = 0; i < datas.size(); i++) {//每次循環創建一行來存儲QuestionXSSFRow row = sheet.createRow(3 + i);//得到每個QuestionQuestion question = datas.get(i);//通過反射獲取每個字段Field[] declaredFields = question.getClass().getDeclaredFields();//遍歷每個字段當做列,因為我實體類中的字段有2個是關聯實體類,就不需要獲取這2列,所有-2.少兩列for (int j = 0; j < declaredFields.length-2; j++) {Field declaredField = declaredFields[j];//暴力反射獲取字段declaredField.setAccessible(true);//獲取到每個字段名Object o = null;try {o = declaredField.get(question);} catch (IllegalAccessException e) {e.printStackTrace();}//每獲取到一個字段就創建一行XSSFCell cell = row.createCell(1 + j);//給這一個格設置值,因為表中的字段有的為null,所以要先判斷一下在寫入,否則會空指針if (o!=null) {//調用toString方法將數據以字符串的形式寫入表格cell.setCellValue(o.toString());}}}//創建文件對象.作為工作薄內容的輸出文件File file = new File("test.xlsx");//輸出時通過流的形式對外輸出try {FileOutputStream fileOutputStream = new FileOutputStream(file);workbook.write(fileOutputStream);//關流workbook.close();} catch (IOException e) {e.printStackTrace();}}/*** 使用POI技術讀取Excel文件*/@Testpublic void ReadExcelByPOI(){//創建讀取的文件工作薄對象XSSFWorkbook sheets = null;try {sheets = new XSSFWorkbook("test.xlsx");} catch (IOException e) {e.printStackTrace();}//獲取工作表對象,第1個,索引從0開始XSSFSheet sheetAt = sheets.getSheetAt(0);//循環讀取表中的行int rowIndex = 2;int cellIndex = 1;while (true){//獲取表中的行XSSFRow row = sheetAt.getRow(rowIndex);while (true){//獲取對應坐標的這一格XSSFCell cell = row.getCell(cellIndex);//讀取格子中的數據String stringCellValue = cell.getStringCellValue();//打印輸出一下System.out.print(stringCellValue+"__");//假設我們知道我們表中有多少列數據,循環多少次cellIndex++;if (cellIndex==14){break;}}//每次讀取一行換一行System.out.println();//將列歸1,索引是從0開始,我們數據在1列才有cellIndex = 1;//假設我們只循環18行數據rowIndex++;if (rowIndex==18){break;}}} }

POI讀的控制臺輸出

poi讀取excel工具類

package com.fs.utils;import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.List; import org.apache.poi.hssf.usermodel.HSSFWorkbook; import org.apache.poi.ss.usermodel.Cell; import org.apache.poi.ss.usermodel.Row; import org.apache.poi.ss.usermodel.Sheet; import org.apache.poi.ss.usermodel.Workbook; import org.apache.poi.xssf.usermodel.XSSFWorkbook; import org.springframework.web.multipart.MultipartFile;public class POIUtils {private final static String xls = "xls";private final static String xlsx = "xlsx";private final static String DATE_FORMAT = "yyyy/MM/dd";/*** 讀入excel文件,解析后返回* @param file* @throws IOException*/public static List<String[]> readExcel(MultipartFile file) throws IOException {//檢查文件checkFile(file);//獲得Workbook工作薄對象Workbook workbook = getWorkBook(file);//創建返回對象,把每行中的值作為一個數組,所有行作為一個集合返回List<String[]> list = new ArrayList<String[]>();if(workbook != null){for(int sheetNum = 0;sheetNum < workbook.getNumberOfSheets();sheetNum++){//獲得當前sheet工作表Sheet sheet = workbook.getSheetAt(sheetNum);if(sheet == null){continue;}//獲得當前sheet的開始行int firstRowNum = sheet.getFirstRowNum();//獲得當前sheet的結束行int lastRowNum = sheet.getLastRowNum();//循環除了第一行的所有行for(int rowNum = firstRowNum+1;rowNum <= lastRowNum;rowNum++){//獲得當前行Row row = sheet.getRow(rowNum);if(row == null){continue;}//獲得當前行的開始列int firstCellNum = row.getFirstCellNum();//獲得當前行的列數int lastCellNum = row.getPhysicalNumberOfCells();String[] cells = new String[row.getPhysicalNumberOfCells()];//循環當前行for(int cellNum = firstCellNum; cellNum < lastCellNum;cellNum++){Cell cell = row.getCell(cellNum);cells[cellNum] = getCellValue(cell);}list.add(cells);}}workbook.close();}return list;}//校驗文件是否合法public static void checkFile(MultipartFile file) throws IOException{//判斷文件是否存在if(null == file){throw new FileNotFoundException("文件不存在!");}//獲得文件名String fileName = file.getOriginalFilename();//判斷文件是否是excel文件if(!fileName.endsWith(xls) && !fileName.endsWith(xlsx)){throw new IOException(fileName + "不是excel文件");}}public static Workbook getWorkBook(MultipartFile file) {//獲得文件名String fileName = file.getOriginalFilename();//創建Workbook工作薄對象,表示整個excelWorkbook workbook = null;try {//獲取excel文件的io流InputStream is = file.getInputStream();//根據文件后綴名不同(xls和xlsx)獲得不同的Workbook實現類對象if(fileName.endsWith(xls)){//2003workbook = new HSSFWorkbook(is);}else if(fileName.endsWith(xlsx)){//2007workbook = new XSSFWorkbook(is);}} catch (IOException e) {e.printStackTrace();}return workbook;}public static String getCellValue(Cell cell){String cellValue = "";if(cell == null){return cellValue;}//如果當前單元格內容為日期類型,需要特殊處理String dataFormatString = cell.getCellStyle().getDataFormatString();if(dataFormatString.equals("m/d/yy")){cellValue = new SimpleDateFormat(DATE_FORMAT).format(cell.getDateCellValue());return cellValue;}//把數字當成String來讀,避免出現1讀成1.0的情況if(cell.getCellType() == Cell.CELL_TYPE_NUMERIC){cell.setCellType(Cell.CELL_TYPE_STRING);}//判斷數據的類型switch (cell.getCellType()){case Cell.CELL_TYPE_NUMERIC: //數字cellValue = String.valueOf(cell.getNumericCellValue());break;case Cell.CELL_TYPE_STRING: //字符串cellValue = String.valueOf(cell.getStringCellValue());break;case Cell.CELL_TYPE_BOOLEAN: //BooleancellValue = String.valueOf(cell.getBooleanCellValue());break;case Cell.CELL_TYPE_FORMULA: //公式cellValue = String.valueOf(cell.getCellFormula());break;case Cell.CELL_TYPE_BLANK: //空值cellValue = "";break;case Cell.CELL_TYPE_ERROR: //故障cellValue = "非法字符";break;default:cellValue = "未知類型";break;}return cellValue;} }

總結

以上是生活随笔為你收集整理的使用POI技术简单的将数据库中的数据读取出为Excel文件的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。