JAVA 將資料庫中的內容轉化為HTML

來源:互聯網
上載者:User

/**
* 將資料庫中的內容轉化為HTML
*data 存在資料庫內欄位的內容
*formId是資料庫內該條資訊的ID
*filePath是產生的html檔案所存放的位置
* @param image
* @return
*/
public void formToHtml(String data, String FormId, String filePath) {
StringBuffer buf = new StringBuffer("");
buf.append("<html>");
buf
.append("<meta http-equiv='Content-Type' content='text/html; charset=utf-8' />");
buf.append("<title>sdsds</title>");
buf.append("<head>");
buf.append("</head>");
buf.append("<body>");
buf.append(data);
buf.append("</body>");
buf.append("</html>");
String fileName = filePath + FormId + ".html";
ObjectOutputStream objOutputStream;
try {
objOutputStream = new ObjectOutputStream(new FileOutputStream(
new File(fileName)));
objOutputStream.writeObject(buf.toString());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

/**
* 將資料庫中的內容轉化為HTML
*vmBasePath vm模板所存放的位置 例如D:\\projectPath\\attach\\html
*vmTempName vm模板的名稱
*dataContext 存在資料庫內欄位的內容
*HtmlFilePath 產生的html所存放的路徑 例如:"D:\\projectPath\\attach\\html\\test.html"
* @param image
* @return
*/
public String dataToHtml(String vmBasePath, String vmTempName,
String dataContext, String HtmlFilePath) throws Exception {
// 初始化並取得Velocity引擎
VelocityEngine ve = new VelocityEngine();
// 設定路徑
Properties properties = new Properties();
String basePath = vmBasePath;
// String basePath = "D:\\projectPath\\attach\\html";
properties.setProperty(Velocity.FILE_RESOURCE_LOADER_PATH, basePath);
ve.init(properties);

// 取得velocity的模版
// Template t = ve.getTemplate("104.vm");
Template t = ve.getTemplate(vmTempName);
// 取得velocity的上下文context
VelocityContext context = new VelocityContext();

// 把資料填入上下文
// context.put("name", "Liang");
context.put("name", dataContext);

// 輸出資料流
StringWriter writer = new StringWriter();

// 轉換輸出
t.merge(context, writer);
// PrintWriter filewriter = new PrintWriter(new
// FileOutputStream("D:\\projectPath\\attach\\html\\test.html"), true);
FileOutputStream fos = new FileOutputStream(HtmlFilePath);
PrintWriter filewriter = new PrintWriter(fos, true);
filewriter.println(writer.toString());

filewriter.flush();
filewriter.close();
fos.flush();
fos.close();
System.out.println("輸出已經完成!");

return "success";
}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.