项目结构:

这是一个maven项目,主函数在Client类里面

当运行程序的后,控制台情况:

当我们刷新了test.html文件后,用浏览器打开效果:

说一下这个过程的设计思路:

1.读取excel文件

2.利用velocity模板工具把读取的内容渲染到html里面

整个过程就两个步骤,是不是非常简单。

当我们在把这两个过程再细化一下,思路就更加清晰明了了。

1.1.怎样读取或者写入Excel文件呢?

java的poi技术读,写Excel[2003-2007,2010]

2.1.怎样使用velocity模板工具呢?

apache的开源项目-模板引擎(Velocity)_学习了两天就上手啦_源码下载

有了上面1.1和2.1的基础,现在我们要做的工作,就是把他们串起来,就实现了Excel转Html

为了自己以后一看源码就知道怎样做,我习惯贴源码出来。 当然还会有源码下载的(在文章末尾)。

===============================================

源码部分:

===============================================

/excel2html/src/main/java/com/b510/excel/client/Client.java

 package com.b510.excel.client;

 import java.util.List;

 import com.b510.excel.common.Common;
import com.b510.excel.reader.ReadExcel;
import com.b510.excel.vo.Student;
import com.b510.excel.writer.WriteHtml; public class Client { public static void main(String[] args) throws Exception {
String excel2010 = Common.STUDENT_INFO_XLSX_PATH;
// read the 2010 excel
List<Student> list1 = new ReadExcel().readExcel(excel2010);
if (list1 != null && list1.size() > 0) {
for (Student student : list1) {
System.out.println("No. : " + student.getNo() + ", name : " + student.getName() + ", age : " + student.getAge() + ", score : " + student.getScore());
}
System.out.println("begin to write into html file");
WriteHtml.write(list1);
} }
}

/excel2html/src/main/java/com/b510/excel/common/Common.java

 package com.b510.excel.common;

 public class Common {

     public static final String OFFICE_EXCEL_2010_POSTFIX = "xlsx";

     public static final String EMPTY = "";
public static final String POINT = ".";
public static final String STUDENT_INFO_XLSX_PATH = "/student_info" + POINT + OFFICE_EXCEL_2010_POSTFIX;
public static final String NOT_EXCEL_FILE = " : Not the Excel file!";
public static final String PROCESSING = "Processing..."; public static final String HTML_FILE = "test.html";
public static final String TEST_HTML_FILE = "./test.html"; }

/excel2html/src/main/java/com/b510/excel/reader/ReadExcel.java

 package com.b510.excel.reader;

 import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List; import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
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 com.b510.excel.common.Common;
import com.b510.excel.util.Util;
import com.b510.excel.vo.Student; public class ReadExcel { /**
* read the Excel file
* @param path the path of the Excel file
* @return
* @throws IOException
*/
public List<Student> readExcel(String path) throws IOException {
if (path == null || Common.EMPTY.equals(path)) {
return null;
} else {
String postfix = Util.getPostfix(path);
if (!Common.EMPTY.equals(postfix)) {
if (Common.OFFICE_EXCEL_2010_POSTFIX.equals(postfix)) {
return readXlsx(path);
}
} else {
System.out.println(path + Common.NOT_EXCEL_FILE);
}
}
return null;
} /**
* Read the Excel 2010
* @param path the path of the excel file
* @return
* @throws IOException
*/
@SuppressWarnings("resource")
public List<Student> readXlsx(String path) throws IOException {
System.out.println(Common.PROCESSING + path);
InputStream is = this.getClass().getResourceAsStream(path);
XSSFWorkbook xssfWorkbook = new XSSFWorkbook(is);
Student student = null;
List<Student> list = new ArrayList<Student>();
// Read the Sheet
for (int numSheet = 0; numSheet < xssfWorkbook.getNumberOfSheets(); numSheet++) {
XSSFSheet xssfSheet = xssfWorkbook.getSheetAt(numSheet);
if (xssfSheet == null) {
continue;
}
// Read the Row
for (int rowNum = 1; rowNum <= xssfSheet.getLastRowNum(); rowNum++) {
XSSFRow xssfRow = xssfSheet.getRow(rowNum);
if (xssfRow != null) {
student = new Student();
XSSFCell no = xssfRow.getCell(0);
XSSFCell name = xssfRow.getCell(1);
XSSFCell age = xssfRow.getCell(2);
XSSFCell score = xssfRow.getCell(3);
student.setNo(getValue(no));
student.setName(getValue(name));
student.setAge(getValue(age));
student.setScore(Float.valueOf(getValue(score)));
list.add(student);
}
}
}
return list;
} /**
* Read the Excel 2003-2007
* @param path the path of the Excel
* @return
* @throws IOException
*/
@SuppressWarnings("resource")
public List<Student> readXls(String path) throws IOException {
System.out.println(Common.PROCESSING + path);
InputStream is = this.getClass().getResourceAsStream(path);
HSSFWorkbook hssfWorkbook = new HSSFWorkbook(is);
Student student = null;
List<Student> list = new ArrayList<Student>();
// Read the Sheet
for (int numSheet = 0; numSheet < hssfWorkbook.getNumberOfSheets(); numSheet++) {
HSSFSheet hssfSheet = hssfWorkbook.getSheetAt(numSheet);
if (hssfSheet == null) {
continue;
}
// Read the Row
for (int rowNum = 1; rowNum <= hssfSheet.getLastRowNum(); rowNum++) {
HSSFRow hssfRow = hssfSheet.getRow(rowNum);
if (hssfRow != null) {
student = new Student();
HSSFCell no = hssfRow.getCell(0);
HSSFCell name = hssfRow.getCell(1);
HSSFCell age = hssfRow.getCell(2);
HSSFCell score = hssfRow.getCell(3);
student.setNo(getValue(no));
student.setName(getValue(name));
student.setAge(getValue(age));
student.setScore(Float.valueOf(getValue(score)));
list.add(student);
}
}
}
return list;
} @SuppressWarnings("static-access")
private String getValue(XSSFCell xssfRow) {
if (xssfRow.getCellType() == xssfRow.CELL_TYPE_BOOLEAN) {
return String.valueOf(xssfRow.getBooleanCellValue());
} else if (xssfRow.getCellType() == xssfRow.CELL_TYPE_NUMERIC) {
return String.valueOf(xssfRow.getNumericCellValue());
} else {
return String.valueOf(xssfRow.getStringCellValue());
}
} @SuppressWarnings("static-access")
private String getValue(HSSFCell hssfCell) {
if (hssfCell.getCellType() == hssfCell.CELL_TYPE_BOOLEAN) {
return String.valueOf(hssfCell.getBooleanCellValue());
} else if (hssfCell.getCellType() == hssfCell.CELL_TYPE_NUMERIC) {
return String.valueOf(hssfCell.getNumericCellValue());
} else {
return String.valueOf(hssfCell.getStringCellValue());
}
}
}

/excel2html/src/main/java/com/b510/excel/util/Util.java

 package com.b510.excel.util;

 import com.b510.excel.common.Common;

 public class Util {

     /**
* get postfix of the path
* @param path
* @return
*/
public static String getPostfix(String path) {
if (path == null || Common.EMPTY.equals(path.trim())) {
return Common.EMPTY;
}
if (path.contains(Common.POINT)) {
return path.substring(path.lastIndexOf(Common.POINT) + 1, path.length());
}
return Common.EMPTY;
}
}

/excel2html/src/main/java/com/b510/excel/vm/student.vm

 <!DOCTYPE html>
<html>
<title>HTML Tutorial</title>
<style>
table {
width:100%;
}
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
th, td {
padding: 5px;
text-align: left;
}
table#t01 tr:nth-child(even) {
background-color: #eee;
}
table#t01 tr:nth-child(odd) {
background-color:#fff;
}
table#t01 th {
background-color: black;
color: white;
}
</style>
<body> <table id="t01">
<tr>
<th>S/N</th>
<th>ID</th>
<th>Name</th>
<th>Age</th>
<th>Score</th>
</tr>
#set( $count = 1 )
#foreach( $student in $students)
<tr>
<td>$count</td>
<td>$student.no</td>
<td>$student.name</td>
<td>$student.age</td>
<td>$student.score</td>
</tr>
#set( $count = $count + 1 )
#end
</table>
</body>
</html>

/excel2html/src/main/java/com/b510/excel/vo/Student.java

 package com.b510.excel.vo;

 public class Student {

     private Integer id;
private String no;
private String name;
private String age;
private float score; public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
} public String getNo() {
return no;
} public void setNo(String no) {
this.no = no;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public String getAge() {
return age;
} public void setAge(String age) {
this.age = age;
} public float getScore() {
return score;
} public void setScore(float score) {
this.score = score;
} }

/excel2html/src/main/java/com/b510/excel/writer/WriteHtml.java

 package com.b510.excel.writer;

 import java.io.File;
import java.io.FileWriter;
import java.io.StringWriter;
import java.util.List; import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine; import com.b510.excel.common.Common;
import com.b510.excel.vo.Student; public class WriteHtml { private static String createCode(String fileVMPath, List<Student> students) throws Exception {
VelocityEngine velocityEngine = new VelocityEngine();
velocityEngine.setProperty("input.encoding", "UTF-8");
velocityEngine.setProperty("output.encoding", "UTF-8");
velocityEngine.init();
Template template = velocityEngine.getTemplate(fileVMPath);
VelocityContext velocityContext = new VelocityContext();
velocityContext.put("students", students);
StringWriter stringWriter = new StringWriter();
template.merge(velocityContext, stringWriter);
return stringWriter.toString();
} public static void write(List<Student> students) throws Exception {
System.out.println("write begin");
File file = new File(Common.TEST_HTML_FILE);
FileWriter fw = new FileWriter(file);
fw.write(createCode("./src/main/java/com/b510/excel/vm/student.vm", students));
fw.flush();
fw.close();
System.out.println("write end. Refresh the project before seeing the excel2html/" + Common.HTML_FILE);
}
}

/excel2html/pom.xml

 <?xml version="1.0"?>
<project
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"
xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<modelVersion>4.0.0</modelVersion> <groupId>hongten.exl2html</groupId>
<artifactId>excel2html</artifactId>
<version>0.0.1</version> <name>excel2html</name>
<url>http://maven.apache.org</url> <properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties> <dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency> <dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.12</version>
</dependency> <dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.12</version>
</dependency> <dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml-schemas</artifactId>
<version>3.12</version>
</dependency> <dependency>
<groupId>velocity</groupId>
<artifactId>velocity</artifactId>
<version>1.5</version>
</dependency> <dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.5</version>
</dependency> <dependency>
<groupId>org.apache.xmlbeans</groupId>
<artifactId>xmlbeans</artifactId>
<version>2.6.0</version>
</dependency> </dependencies>
</project>

源码下载:http://files.cnblogs.com/files/hongten/excel2html.zip

========================================================

More reading,and english is important.

I'm Hongten

大哥哥大姐姐,觉得有用打赏点哦!多多少少没关系,一分也是对我的支持和鼓励。谢谢。
Hongten博客排名在100名以内。粉丝过千。
Hongten出品,必是精品。

E | hongtenzone@foxmail.com  B | http://www.cnblogs.com/hongten

========================================================

Excel转Html的更多相关文章

  1. 【造轮子】打造一个简单的万能Excel读写工具

    大家工作或者平时是不是经常遇到要读写一些简单格式的Excel? shit!~很蛋疼,因为之前吹牛,就搞了个这东西,还算是挺实用,和大家分享下. 厌烦了每次搞简单类型的Excel读写?不怕~来,喜欢流式 ...

  2. excel 日期/数字格式不生效需要但双击才会生效的解决办法

    原因: Excel2007设置过单元格格式后,并不能立即生效必须挨个双击单元格,才能生效.数据行很多.效率太低. 原因:主要是一些从网上拷贝过来的日期或数字excel默认为文本格式或特殊-中文数字格式 ...

  3. C# Excel导入、导出【源码下载】

    本篇主要介绍C#的Excel导入.导出. 目录 1. 介绍:描述第三方类库NPOI以及Excel结构 2. Excel导入:介绍C#如何调用NPOI进行Excel导入,包含:流程图.NOPI以及C#代 ...

  4. Word/Excel 在线预览

    前言 近日项目中做到一个功能,需要上传附件后能够在线预览.之前也没做过这类似的,于是乎就查找了相关资料,.net实现Office文件预览大概有这几种方式: ① 使用Microsoft的Office组件 ...

  5. ASP.NET MVC5+EF6+EasyUI 后台管理系统(63)-Excel导入和导出-自定义表模导入

    系列目录 前言 上一节使用了LinqToExcel和CloseXML对Excel表进行导入和导出的简单操作,大家可以跳转到上一节查看: ASP.NET MVC5+EF6+EasyUI 后台管理系统(6 ...

  6. C#中如何给Excel添加水印

    我们知道Microsoft Excel并没有内置的功能直接给Excel表添加水印,但是其实我们可以用其他变通的方式来解决此问题,如通过添加页眉图片或艺术字的方法来模仿水印的外观.所以在这篇文章中,我将 ...

  7. C#中如何在Excel工作表创建混合型图表

    在进行图表分析的时候,我们可能需要在一张图表呈现两个或多个样式的图表,以便更加清晰.直观地查看不同的数据大小和变化趋势.在这篇文章中,我将分享C#中如何在一张图表中创建不同的图表类型,其中包括如何在同 ...

  8. 【C#附源码】数据库文档生成工具支持(Excel+Html)

    [2015] 很多时候,我们在生成数据库文档时,使用某些工具,可效果总不理想,不是内容不详细,就是表现效果一般般.很多还是word.html的.看着真是别扭.本人习惯用Excel,所以闲暇时,就简单的 ...

  9. 免费高效实用的.NET操作Excel组件NPOI(.NET组件介绍之六)

    很多的软件项目几乎都包含着对文档的操作,前面已经介绍过两款操作文档的组件,现在介绍一款文档操作的组件NPOI. NPOI可以生成没有安装在您的服务器上的Microsoft Office套件的Excel ...

  10. C#通过NPOI操作Excel

    参考页面: http://www.yuanjiaocheng.net/webapi/create-crud-api-1-post.html http://www.yuanjiaocheng.net/w ...

随机推荐

  1. spring 参数绑定

    部分资料来源: @RequestParam @RequestBody @PathVariable 等参数绑定注解详解 spring学习之@ModelAttribute运用详解 Spring MVC @ ...

  2. Redis Cluster 介绍与使用

    Redis Cluster 功能特性 Redis 集群是分布式的redis 实现,具有以下特性: 1. 高可用性与可线性扩张到1000个节点 2. 数据自动路由到多个节点 3. 节点间数据共享 4. ...

  3. http://blog.csdn.net/java2000_wl/article/details/8627874

    http://blog.csdn.net/java2000_wl/article/details/8627874

  4. javascrit原生实现jquery的append()函数

    /** * javascrit原生实现jquery的append()函数 * @param parent * @param text */ function append(parent, text) ...

  5. The difference between QA, QC, and Test Engineering

    Tuesday, March 06, 2007 Posted by Allen Hutchison, Engineering Manager and Jay Han, Software Enginee ...

  6. Git 常用操作和问题解决

    记录一下自己用git作为项目管理过程中常见的错误以及处理方法 1.git pull 出现问题 git pull出现的问题多为远程分支文件和本地冲突 错误提示:error: Your local cha ...

  7. es6要用严格模式

    实验let的块级作用域,在sublime的Tools--Babel--Babel Transform检测未出现错误,在html中也未出现错误,唯在控制台中一直报错. //js名为es6.js ---* ...

  8. mac显示任何来源

    p.p1 { margin: 0.0px 0.0px 0.0px 0.0px; font: 16.0px "Microsoft YaHei"; color: #333333; ba ...

  9. python之系统性能信息模块psutil

    系统性能信息模块psutil 跨平台库 轻松实现获取系统运行的进程和系统利用率(包括CPU.内存.磁盘.网络等)信息. 主要用于系统监控,分析和限制系统资源及进程的管理 实现同等命令行工具提供的功能( ...

  10. NOPI读取模板导出(Excel中追加数据)

    在Controller里,我们定义一个FileResult的Action,返回值是一个文件形式被浏览器下载下来. [HttpGet] public FileResult ExportProductLi ...