Java Excel基於POI利用反射匯入匯出、基於jxls的Excel模板匯出
自述:專案中一直沒有一個好用的Excel匯入匯出功能。所以簡單實現了匯入匯出功能供大家參考
匯入功能:基於poi匯入做了一層封裝、支援註解方式標識屬性對應Excel列、並支援簡單規則校驗、具體規則校驗可以根據自己需求自定義
兩種匯出功能:一種基於poi的匯出,一種基於jxls模板匯出。jxls模板匯出可參考:jxls說明
別的就不多BB了,直接上程式碼。原始碼包可直接下載使用:點我取原始碼
1、基於maven專案的新增依賴,POM依賴如下
<!-- Excel poi檔案處理 --> <dependency> <groupId>commons-beanutils</groupId> <artifactId>commons-beanutils</artifactId> <version>1.8.0</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi-ooxml</artifactId> <version>3.9</version> </dependency> <!-- Excel模板匯出依賴 --> <dependency> <groupId>net.sf.jxls</groupId> <artifactId>jxls-core</artifactId> <version>1.0.6</version> </dependency> <dependency> <groupId>net.sf.jxls</groupId> <artifactId>jxls-reader</artifactId> <version>1.0.6</version> </dependency> <dependency> <groupId>org.apache.ant</groupId> <artifactId>ant</artifactId> <version>1.9.4</version> </dependency>
2、Excle匯入類ExcelException.java,ExcelFieldMeta.java,ExcelUtil.java,入口類為ExcelUtil.java裡面提供各種靜態方法
ExcelUtil.java
/** * Excel匯入 * * @author http://blog.csdn.net/make_a_difference */ @SuppressWarnings("unchecked") public class ExcelUtil { private static Log logger = LogFactory.getLog(ExcelUtil.class); // 換行標識 private final static String ENTER_STR = "\n"; /** * 預設解析Excel第一個sheet頁 * * @param is * 輸入流 * @param startRow * 開始解析行 * @param clazz * 實體類 * @return * @throws ExcelException */ public static <T> List<T> excelParsing(InputStream is, Integer startRow, Class<T> clazz) throws ExcelException { return excelParsing(is, 1, startRow, clazz); } /** * 預設解析Excel第一個sheet頁 * * @param is * 輸入流 * @param startRow * 開始解析行 * @param clazz * 實體類 * @return * @throws ExcelException * @throws FileNotFoundException */ public static <T> List<T> excelParsing(File file, Integer startRow, Class<T> clazz) throws ExcelException { FileInputStream is; try { is = new FileInputStream(file); } catch (FileNotFoundException e) { logger.error("Excel檔案異常", e); throw new ExcelException("Excel檔案異常"); } return excelParsing(is, 1, startRow, clazz); } /** * 解析Excel * * @param is * 輸入流 * @param sheetIndex * sheet頁數 * @param startRow * 開始解析行 * @param clazz * 實體類 * @return * @throws ExcelException */ public static <T> List<T> excelParsing(InputStream is, Integer sheetIndex, Integer startRow, Class<T> clazz) throws ExcelException { // 1: 獲取工作簿 Workbook wb = null; try { wb = ExcelUtil.getWorkbook(is); } catch (Exception e) { logger.error("系統解析Excel獲取WorkBook錯誤", e); throw new ExcelException("系統解析Excel錯誤"); } // 2:獲取第一個sheet頁碼 Sheet sheet = wb.getSheetAt(sheetIndex - 1); return doParsing(sheet, startRow, clazz); } @SuppressWarnings("rawtypes") private static <T> List<T> doParsing(Sheet sheet, Integer startRow, Class<T> clazz) throws ExcelException { StringBuffer errorMessage = new StringBuffer(""); // 1:獲取sheet頁的總行數 int lastRow = sheet.getLastRowNum(); // 2: 行解析,預設從0開始,startRow屬性定義了資料從該行開始解析,程式中定義的行數從1開始算,所以此處要-1 List resultList = new ArrayList(3); try { for (int rowIndex = startRow - 1; rowIndex <= lastRow; rowIndex++) { Row row = sheet.getRow(rowIndex); // 得到 第 n 行 // 2.1獲取的列為空則跳出迴圈 if (row == null) { continue; } // 2.2 解析物件 Object rowBean = clazz.newInstance(); String rowErrorMessage = check(row, rowIndex, rowBean); // 2.3 如果返回的不是null,則存在錯誤資訊則記錄錯誤資訊 if (rowErrorMessage != null) { errorMessage.append(rowErrorMessage + ENTER_STR); continue; } else if ("end".equals(rowErrorMessage)) { resultList.add(rowBean); return resultList; } // 2.4 如果正確 則不讀取 resultList.add(rowBean); } } catch (Exception e) { logger.error("系統解析Excel列錯誤", e); throw new ExcelException("系統解析Excel錯誤"); } // 3:如果存在錯誤則需要將異常丟擲 if (errorMessage.length() > 0) { throw new ExcelException(errorMessage.toString()); } return resultList; } /** * * @param row * 行資訊 * @param rowIndex * 當前行數 * @param declaredFields * @param rowBean * @return 錯誤資訊 * @throws Exception */ private static String check(Row row, int rowIndex, Object rowBean) throws Exception { // 1: 物件中迴圈取資料並賦值 for (Field field : rowBean.getClass().getDeclaredFields()) { // 2:包含excel規則校驗的註解 ExcelFieldMeta meta = field.getAnnotation(ExcelFieldMeta.class); // 3:單元格的值 Cell cell = row.getCell(meta.cell() - 1); String cellValue = getCellValue(cell); Object obejctVal = null; // 3.1 第一個單元並單元格值為空則表示讀取excel結束 if (meta.cell() == 1 && (cell == null || "".equals(cellValue) || "null".equals(cellValue))) return "end"; // 4.2校驗單元格是否必填,單元格可以為空 if (!meta.isNotNull() && (cellValue == null || "".equals(cellValue))) { continue; } // 4.2:可以為空且為空 if (meta.isNotNull() && (cellValue == null || "".equals(cellValue))) { return "[" + (rowIndex + 1) + "]行-[" + (meta.cell()) + "]列:此單元格內容不能為空值"; } // 4.3 整型、浮點型 if (field.getType() == Integer.class) { try { // 此處採用浮點數轉換,驗證value中是否含有字元。整形轉換時只要整數部分的資料 obejctVal = (int) cell.getNumericCellValue(); } catch (Exception ne) { return "[" + (rowIndex + 1) + "]行-[" + (meta.cell()) + "]列:此單元格內容只能為數值,讀取時為:" + cellValue; } } else if (field.getType() == Double.class) {// 4.4 浮點型 try { // 此處採用浮點數轉換,驗證value中是否含有字元。整形轉換時只要整數部分的資料 obejctVal = cell.getNumericCellValue(); } catch (NumberFormatException ne) { return "[" + (rowIndex + 1) + "]行-[" + (meta.cell()) + "]列:此單元格內容只能為數值,讀取時為:" + cellValue; } } else if (field.getType() == Date.class) {// 4.5處理日期型別 SimpleDateFormat sf = new SimpleDateFormat(meta.dateFormat()); try { obejctVal = sf.parse(cellValue); obejctVal.toString(); } catch (ParseException e) { return "[" + (rowIndex + 1) + "]行-[" + (meta.cell()) + "]列:此單元格內容中日期格式異常,讀取時為" + cellValue; } } else if (field.getType() == String.class) { obejctVal = cellValue; } // 4.6 長度校驗 if (meta.maxLength() != -1 && cellValue.length() > meta.maxLength()) { return "[" + (rowIndex + 1) + "]行-[" + (meta.cell()) + "]列:此單元格內容的長度不能超出" + meta.maxLength() + "個字元"; } // 4.7設定屬性 PropertyUtils.setProperty(rowBean, field.getName(), obejctVal); } return null; } /** * 得到當前列的值 * * @param cell * @return */ private static String getCellValue(Cell cell) { String typeString = ""; if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) { typeString = String.valueOf(cell.getNumericCellValue()); } else if (cell.getCellType() == Cell.CELL_TYPE_STRING) { typeString = String.valueOf(cell.getStringCellValue()); } else if (cell.getCellType() == Cell.CELL_TYPE_FORMULA) { typeString = String.valueOf(cell.getDateCellValue()); } else if (cell.getCellType() == Cell.CELL_TYPE_BLANK) { typeString = String.valueOf(cell.getStringCellValue()); } else if (cell.getCellType() == Cell.CELL_TYPE_ERROR) { typeString = ""; } return typeString; } /** * 解析不同版本的Excel檔案 * * @param in * @return * @throws IOException * @throws InvalidFormatException */ private static Workbook getWorkbook(InputStream in) throws IOException, InvalidFormatException { if (!in.markSupported()) { in = new PushbackInputStream(in, 8); } if (POIFSFileSystem.hasPOIFSHeader(in)) { return new HSSFWorkbook(in); } if (POIXMLDocument.hasOOXMLHeader(in)) { try { return new XSSFWorkbook(OPCPackage.open(in)); } catch (InvalidFormatException e) { logger.error("Excel檔案異常", e); } } throw new IllegalArgumentException("你的excel版本目前poi不支援"); }
ExcelFieldMeta.java
ExcelException.java/** * Excel物件自定義註解 * * @author http://blog.csdn.net/make_a_difference * */ @Retention(RetentionPolicy.RUNTIME) // 註解會在class位元組碼檔案中存在,在執行時可以通過反射獲取到 @Target({ ElementType.FIELD, ElementType.METHOD }) // 定義註解的作用目標**作用範圍欄位、列舉的常量/方法 @Documented // 說明該註解將被包含在javadoc中 public @interface ExcelFieldMeta { // 對應Excel文件中的列號 int cell() default 0; // 不能為空,預設為 是 boolean isNotNull() default true; // 最大長度, -1 則不限制 int maxLength() default -1; // 日期格式,預設匯入格式為"yyyy/MM/dd"如"2015/5/13" String dateFormat() default "yyyy/MM/dd"; }
/**
* Excel處理異常
*
* @author http://blog.csdn.net/make_a_difference
*/
public class ExcelException extends Exception {
/**
* @Fields serialVersionUID: (用一句話描述這個變量表示什麼)
*/
private static final long serialVersionUID = 1L;
public ExcelException() {
super();
}
public ExcelException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
public ExcelException(String message, Throwable cause) {
super(message, cause);
}
public ExcelException(String message) {
super(message);
}
public ExcelException(Throwable cause) {
super(cause);
}
}
3、Excel基於POI匯出參考程式碼/**
* Excel下載
*
* @author http://blog.csdn.net/make_a_difference
*/
public class ExcelExport {
/**
* 下載excel檔案,內容使用MAP存放 。 支援多個sheet。兩個map的長度必須一致,map的key為索引(index)
*
* @param response
* 響應流
* @param headName
* Excel表名
* @param tableHeadMap
* 每個sheet對應的表頭為具體的value值
* @param tableBodyMap
* 每個sheet對應的內容為具體的value值
*/
public static void downloadExcelMap(HttpServletResponse response, String headName,
Map<Integer, List<String>> tableHeadMap, Map<Integer, List<Map<Object, Object>>> tableBodyMap)
throws Exception {
headName = replaceAllSpecial(headName);
// 1:建立一個workbook
Workbook workbook = new HSSFWorkbook();
// 建立樣式
CellStyle style = workbook.createCellStyle();
Font font = workbook.createFont();
font.setBoldweight(Font.BOLDWEIGHT_BOLD); // 粗體
style.setFont(font);
style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 水平居中
style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); // 垂直居中
style.setBorderTop((short) 1);
style.setBorderBottom((short) 1);
style.setBorderLeft((short) 1);
style.setBorderRight((short) 1);
// 設定合計樣式
CellStyle style1 = workbook.createCellStyle();
style1.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 水平居中
style1.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); // 垂直居中
style1.setBorderTop((short) 1);
style1.setBorderBottom((short) 1);
style1.setBorderLeft((short) 1);
style1.setBorderRight((short) 1);
int sheetLength = tableHeadMap.size();
if (sheetLength != tableBodyMap.size()) {
throw new Exception("tableHeadMap與tableBodyMap對應的長度不一致");
}
for (int i = 0; i < sheetLength; i++) {
Sheet sheet = workbook.createSheet(headName + (i + 1));
List<String> tableHead = tableHeadMap.get(i);
List<Map<Object, Object>> tableBody = tableBodyMap.get(i);
// 2:合併單元格,表頭。並設定值
CellRangeAddress cra = new CellRangeAddress(0, 0, 0, tableHead.size() - 1);
sheet.addMergedRegion(cra);
Row row = sheet.createRow(0);
Cell tableName = row.createCell(0);
tableName.setCellStyle(style);
tableName.setCellValue(headName);
// 3:設定表head
Row row1 = sheet.createRow(1);
for (int m = 0; m < tableHead.size(); m++) {
Cell createCell = row1.createCell(m);
createCell.setCellValue(tableHead.get(m));
createCell.setCellStyle(style);
}
// 4:表格內容
for (int m = 0; m < tableBody.size(); m++) {
Row rows = sheet.createRow(m + 2);
int j = 0;
for (Map.Entry<Object, Object> entry : tableBody.get(m).entrySet()) {
Cell createCell = rows.createCell(j);
if (entry.getValue() != null && !"".equals(entry.getValue())) {
createCell.setCellValue(entry.getValue().toString());
} else {
createCell.setCellValue("");
}
createCell.setCellStyle(style1);
j++;
}
}
}
// 5:設定頭
response.setHeader("Content-disposition",
"attachment; filename=" + new String(headName.getBytes("GB2312"), "ISO8859-1") + ".xls");
// 6:設定頭型別
response.setContentType("application/vnd.ms-excel");
// 7:寫出
OutputStream toClient = response.getOutputStream();
workbook.write(toClient);
toClient.flush();
toClient.close();
}
/**
* 下載excel檔案,內容使用MAP存放
*
* @param response
* 響應流
* @param headName
* Excel檔名
* @param tableHead
* 表的title
* @param tableBody
* 表內容
* @throws IOException
*/
public static void downloadExcelMap(HttpServletResponse response, String headName, List<String> tableHead,
List<Map<Object, Object>> tableBody) throws IOException {
headName = replaceAllSpecial(headName);
// 1:建立一個workbook
Workbook workbook = new HSSFWorkbook();
// 建立樣式
CellStyle style = workbook.createCellStyle();
Font font = workbook.createFont();
font.setBoldweight(Font.BOLDWEIGHT_BOLD); // 粗體
style.setFont(font);
style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 水平居中
style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); // 垂直居中
style.setBorderTop((short) 1);
style.setBorderBottom((short) 1);
style.setBorderLeft((short) 1);
style.setBorderRight((short) 1);
// 設定合計樣式
CellStyle style1 = workbook.createCellStyle();
style1.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 水平居中
style1.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER); // 垂直居中
style1.setBorderTop((short) 1);
style1.setBorderBottom((short) 1);
style1.setBorderLeft((short) 1);
style1.setBorderRight((short) 1);
Sheet sheet = workbook.createSheet(headName);
// 2:合併單元格,表頭。並設定值
CellRangeAddress cra = new CellRangeAddress(0, 0, 0, tableHead.size() - 1);
sheet.addMergedRegion(cra);
Row row = sheet.createRow(0);
Cell tableName = row.createCell(0);
tableName.setCellStyle(style);
tableName.setCellValue(headName);
// 3:設定表head
Row row1 = sheet.createRow(1);
for (int i = 0; i < tableHead.size(); i++) {
Cell createCell = row1.createCell(i);
createCell.setCellValue(tableHead.get(i));
createCell.setCellStyle(style);
}
// 4:表格內容
for (int i = 0; i < tableBody.size(); i++) {
Row rows = sheet.createRow(i + 2);
int j = 0;
for (Map.Entry<Object, Object> entry : tableBody.get(i).entrySet()) {
Cell createCell = rows.createCell(j);
if (entry.getValue() != null && !"".equals(entry.getValue())) {
createCell.setCellValue(entry.getValue().toString());
} else {
createCell.setCellValue("");
}
createCell.setCellStyle(style1);
j++;
}
}
// 5:設定頭
response.setHeader("Content-disposition",
"attachment; filename=" + new String(headName.getBytes("GB2312"), "ISO8859-1") + ".xls");
// 6:設定頭型別
response.setContentType("application/vnd.ms-excel");
// 7:寫出
OutputStream toClient = response.getOutputStream();
workbook.write(toClient);
toClient.flush();
toClient.close();
}
/**
* 下載excel檔案,內容使用MAP存放
*
* @param response
* 響應流
* @param headName
* Excel檔名
* @param tableHead
* 表的title
* @param tableBody
* 表內容
* @throws IOException
*/
public static void downloadExcelObj(HttpServletResponse response, String headName, List<String> tableHead,
List<Object> tableBody) throws Exception {
// 將物件轉換成map
List<Map<Object, Object>> mapBody = new ArrayList<Map<Object, Object>>();
for (int i = 0; i < tableBody.size(); i++) {
Map<Object, Object> objectMap = new LinkedHashMap<Object, Object>();
Field[] fields = tableBody.get(i).getClass().getDeclaredFields();
for (Field v : fields) {
v.setAccessible(true);
Object va = v.get(tableBody.get(i));
if (va == null) {
va = "";
}
objectMap.put(v.getName(), va);
}
mapBody.add(objectMap);
}
downloadExcelMap(response, headName, tableHead, mapBody);
}
/**
* 替換特殊字元
*
* @param str
* @return
*/
private static String replaceAllSpecial(String str) {
String regEx = "[`[email protected]#$%^&*()+=|{}':;',\\[\\].<>/?~!@#¥%……&*()——+|{}【】‘;:”“’。,、?]";
Pattern p = Pattern.compile(regEx);
Matcher m = p.matcher(str);
return m.replaceAll("").trim();
}
}
3、Excel基於jxls模板匯出參考程式碼
/**
* Excel 模板下載
*
* @author http://blog.csdn.net/make_a_difference
*/
public class ExcelTempletExport {
/**
* 通過模板下載Excel檔案
* <jx:forEach items="${list}" var="bean"> ${bean.courseName} </jx:forEach>
*
* @param templateUrl
* 模板路徑 /org/gtiles/components/gtclasses/workbench/
* teacherfacecoursecount/list/templateTeacherCourse.xlsx
* @param tableBody
* 輸出內容list
* @param fileName
* 檔名稱
* @param response
* 相應流
*
* @throws Exception
*/
public static void downloadExcel(String templatePath, List<?> tableBody, String fileName,
HttpServletResponse response) throws Exception {
Map<String, Object> beanParams = new HashMap<String, Object>();
beanParams.put("list", tableBody);
downloadExcel(templatePath, beanParams, fileName, response);
}
/**
* 通過模板下載Excel檔案
* <jx:forEach items="${list}" var="bean"> ${bean.courseName} </jx:forEach>
*
* @param templateUrl
* 模板路徑 /org/gtiles/components/gtclasses/workbench/
* teacherfacecoursecount/list/templateTeacherCourse.xlsx
* @param map
* 輸出內容 key-value
* @param fileName
* 檔名稱
* @param response
* 相應流
*
* @throws Exception
*/
public static void downloadExcel(String templatePath, Map<String, Object> map, String fileName,
HttpServletResponse response) throws Exception {
// 1: 建立XLSTransformer物件
XLSTransformer transformer = new XLSTransformer();
// 2:獲取模板,讀取jar檔案並返回流
InputStream is = ExcelTempletExport.class.getResourceAsStream(templatePath);
try {
// 4:設定響應頭
response.setHeader("Content-Disposition",
"attachment;filename=\"" + new String(fileName.getBytes("gb2312"), "iso8859-1") + ".xlsx\"");
response.setContentType("application/vnd.ms-excel");
// 5:通過流向客戶端寫資料
transformer.transformXLS(is, map).write(response.getOutputStream());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (is != null)
is.close();
response.getOutputStream().flush();
response.getOutputStream().close();
}
}
/**
* 通過模板將Excel寫入到另外一個Excel檔案中
*
* @param srcFilePath
* 模板路徑
* @param tableBody
* 輸出內容
* @param destFilePath
* 輸出目標檔案
* @throws Exception
*/
public static void downloadExcel(String srcFilePath, List<?> tableBody, String destFilePath) throws Exception {
// 1: 建立XLSTransformer物件
XLSTransformer transformer = new XLSTransformer();
// 2:將資料轉換成Map格式
Map<String, Object> beanParams = new HashMap<String, Object>();
beanParams.put("list", tableBody);
// 3:寫出檔案
transformer.transformXLS(srcFilePath, beanParams, destFilePath);
}
}
4、Test 測試匯入
/**
* test
* @author http://blog.csdn.net/make_a_difference
*/
public class TestBean {
@ExcelFieldMeta(cell = 1)
private String name;
@ExcelFieldMeta(cell = 2, isNotNull = false)
private Integer age;
@ExcelFieldMeta(cell = 3)
private Date birthday;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public static void main(String[] args) throws FileNotFoundException {
try {
// List<TestBean> excelParsing = ExcelUtil.excelParsing(new File("C:\\Users\\Administrator\\Desktop\\test.xlsx"), 1, TestBean.class);
//1:匯入
List<TestBean> excelParsing = ExcelUtil.excelParsing(new FileInputStream("C:\\Users\\Administrator\\Desktop\\test.xlsx"), 1, 1, TestBean.class);
//2:匯出
ExcelTempletExport.downloadExcel("模板路徑",excelParsing, "檔名", response);
} catch (ExcelException e) {
System.out.println(e.toString());//excel解析的錯誤。例:[2]行-[2]列:此單元格內容只能為數值,讀取時為:qx
}
}
Excel匯入模板
Excel使用jxls匯出模板
相關推薦
Java Excel基於POI利用反射匯入匯出、基於jxls的Excel模板匯出
自述:專案中一直沒有一個好用的Excel匯入匯出功能。所以簡單實現了匯入匯出功能供大家參考匯入功能:基於poi匯入做了一層封裝、支援註解方式標識屬性對應Excel列、並支援簡單規則校驗、具體規則校驗可以根據自己需求自定義兩種匯出功能:一種基於poi的匯出,一種基於jxls模板
【小家java】一個基於POI的Excel的匯入、匯出工具處理類(支援xls,xlsx格式),另有SpringMVC的匯入、匯出案例講解
相關閱讀 前言 表格的匯入、匯出可謂開發過程中經常會碰到的功能。然後這種模版化的東西並不需要每次都去編碼一次,因此我就整理了一個Excel的萬能處理類。能夠實現相容2003、2007的各種Excel格式的匯入匯出功能,使用起來也非常的方面,適用於所有業務場景
Java中使用poi匯入、匯出Excel
一、介紹 當前B/S模式已成為應用開發的主流,而在企業辦公系統中,常常有客戶這樣子要求:你要把我們的報表直接用Excel開啟(電信系統、銀行系統)。或者是:我們已經習慣用Excel列印。這樣在我們實際的開發中,很多時候需要實現匯入、匯出Excel的應用。 目前,比較
一個基於POI的通用excel匯入匯出工具類的簡單實現及使用方法
前言: 最近PM來了一個需求,簡單來說就是在錄入資料時一條一條插入到系統顯得非常麻煩,讓我實現一個直接通過excel匯入的方法一次性錄入所有資料。網上關於excel匯入匯出的例子很多,但大多相互借鑑。經過思考,認為一百個客戶在錄入excel的時候,就會有一百個格式版本,所以在實現這個功能之前,所以要統一exc
JAVA語言工具類封裝-基於poi的excel匯出功能
http://blog.csdn.net/caisini_vc/article/details/52387842 excel匯出基本上是必備的功能,如果條目超過65535 是csv,否則xls。 一句話使用: OrderInfoExcelBuilder.g
JAVA實現資料庫資料匯入/匯出到Excel(POI技術)
準備工作: 1.匯入POI包:POI下載地址:http://download.csdn.net/detail/zxm1306192988/9522142(重要) 如下 2.匯入匯出到Excel工具類ExcelUtil.java,封裝了POI對Excel的操作 pa
Java使用POI匯出Excel工具類(反射)
pom.xml: <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId&g
基於 POI 封裝 ExcelUtil 精簡的 Excel 匯入匯出
由於 poi 本身只是針對於 excel 等office軟體的一個工具包,在一些常規的 excel 匯入匯出時,還需要再做一次精簡的封裝,簡化程式碼耦合。 一、現狀 本人經歷過幾家公司的程式碼封裝,匯入匯出一般存在下面的情況。 1.1 匯入 傳入檔案地址,返回 Sheet
Java型別資訊與用反射機制編寫通用的Excel匯入匯出
Java類檔案編譯後,會在類中新增一個靜態屬性,這個屬性就是Class類的例項,用於描述型別資訊。描述類資訊的架構圖如: Class物件提供了一組方法,讓我們可以方便獲取類的屬性,方法,構造方法等資訊,並且用Field,Method,Constructor類
在SSM下基於POI實現Excel表的匯入/匯出
對於批量資料的操作,在專案中引進Excel的匯入和匯出功能是個不錯的選擇。對於Excel表的結構,簡單理解可以把它分成三部分(Sheet,Cell,Row),這三部分可以理解為excel表中的頁,列,行。因此,我們想要獲取到某一個單元的內容,可以通過獲取該單元所在的頁數、對應
POI和Java Excel Api匯入匯出----詳細到你不敢相信
來自:http://blog.csdn.net/jerehedu/article/details/45195359 一、介紹 當前B/S模式已成為應用開發的主流,而在企業辦公系統中,常常有客戶這樣子要求:你要把我們的報表直接用
java利用POI通過模板匯出excel的一個例項
寫之前,大家請先下好poi的相關jar包,網上遍地都是,不多說 <input type="button" id="exportBtn" class="CommonBtn" value="匯出Excel" /> 這個是按鈕 這個是相關事件
Java Excel匯入匯出,基於XML和Easy-excel使用
1.前言 •在工作時,遇到過這樣的需求,需要靈活的對工單進行匯入或匯出,以前自己也做過,但使用不靈活繁瑣。我想能不能像配置檔案一樣可配置的匯入匯出,那樣使用起來就方便許多。 2.SpringMVC專案搭建 •建立基於Maven版本管理Springmvc專案
java excel大資料量匯入匯出與優化
package com.hundsun.ta.utils; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java
JAVA 匯出EXCEL表格 POI
今天給大家帶來javaweb專案使用poi匯出excel的入門示例,適用於初次接觸的新手。匯出excel分兩步:1、生成一個excel放在工作目錄下,2、把它匯出到本地。 請讀者自行下載所需jar包,如圖: 然後將jar包引入 接下來放程式碼。程式碼看起來複雜,其實稍微一分析
Java io操作,poi匯出excel,集合自帶排序,日誌報告
java io操作,poi匯出到excel表格,sl4j日誌列印,集合自帶排序Comparator要求: 取出txt檔案中其中第50000行到60000行的資料,進行資料的解析,然後對資料的某一項進行排序,從小到大輸出到excel表格中.每一步的錯誤進行日誌列印,不要直接e
Java後臺程式碼實現POI檔案的匯入匯出
前言 工作中常常會用到POI的匯入匯出功能,今天為大家詳細介紹一下平時用到的最多的匯入Excel表格資料和匯出資料為Excel表格的相關程式碼操作!本案例是SpringBoot專案,廢話不多說上程式碼! 1.Controller層程式碼 //相關導包 import
js實現Excel檔案匯入匯出、利用 js-xlsx 實現 Excel 檔案匯入匯出-功能示例
1.匯入功能實現 下載js-xlsx到dist複製出xlsx.full.min.js引入到頁面中 然後通過FileReader物件讀取檔案利用js-xlsx轉成json資料 <!DOCTYPE html> <html> <head>
java基於poi的excel表格處理(自定義註解、針對List與enum進行處理)
Java基於poi的excel表格處理 背景: 由於網上太少有方便的工具來操作了,所以手動造了個輪子… 例子: 說明: 在欄位上新增@ExcelInfo註解,其中row為“行數-1”,col為“列數-1”。 如需進行特
關於Java Web 使用 POI 將 資料庫表 匯出 Excel 的完整例項
//匯出Excel public void exportExcel() throws InterruptedException, IOException{ HSSFWorkbook hwb = new HSSFWorkbook();//第一步,建立一個workbook