有天老板找我到辦公室跟我說要做一個商城,商城賣出去東西就有傭金可以拿。我聽著就頭大。老板打開電腦給我看了網站:你看一下這個網站,照著它的流程就可以擁有一個商城了。我靠過去一看,大概了解一下:原來是利用第三方工具就可以構建一個導購網站,只要消費者在網站領取優惠券就會自動跳轉到某bao的購買頁面,購買成功后就可以有傭金了。我看了一下覺得可以,只要不讓我敲代碼一切好說。于是我照著流程構建了一個網站,然后勾選了很多零食進行推廣,然后我就發現了一個問題:我只勾選了一些零食啊,商城怎么還有其它類型的商品?我思索了一下就明白了,這網站還是挺流氓的,還摻雜著其他人的推廣鏈接,我一想這樣不行,轉化率肯定低啊。果不其然,試用了一天就只有5個單子,因為公司的網站還是挺有流量的,所以這轉化率不可能這么低。老板看了一下,覺得沒什么用讓我把商城入口給關了,我只好照做,但是我心里對這流氓網站不服啊,于是我打算自己做一個導購網站。(最后還是要敲代碼(。?_?)/~~~)
1. 安裝xlrd
cmd窗口: pip install xlrd
2.創建index.py,導入模塊
import xlrd
3.打開Excel文件讀取數據
wb= xlrd.open_workbook('文件路徑')
4.獲取表格
sheet1 = wb.sheet_by_index(0) #這里的excel文檔內只有一個表格,0代表第一個
5.獲取表格的行數
rows = sheet1.nrows
6.獲取表格中的類目
商品一級類目
住宅家具
影音電器
影音電器
美容護膚
廚房電器
運動服/休閑服裝
餐飲具
category0 = sheet1.col_values(4) #獲取列內容(類目),這里excel文檔的第四列是類目 del category0[0] #刪除列表中的 "商品一級類目" category = sorted(set(category0),key=category0.index) #類目列表->去除重復
7.整理數據
[ [ 分類名, [商品信息] ], [ 分類名, [商品信息] ] ] data = [] for i,v in enumerate(category): data.append([v,[]]) for i,v in enumerate(data): for x in range(rows): if v[0] == sheet1.cell(x,4).value: data[i][1].append(sheet1.row_values(x))
8.導出json文件
jsonData = json.dumps(data, ensure_ascii=False) with open('results.json', 'w',encoding="utf-8") as f: f.write(jsonData)
9.運行index.py,獲得json文件
cmd窗口:python index.py
10.創建html頁面,并引用json文件
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script> <script>//引用jquery $(function(){ function color16(){//十六進制顏色隨機 var r = Math.floor(Math.random()*256); var g = Math.floor(Math.random()*256); var b = Math.floor(Math.random()*256); var color = '#'+r.toString(16)+g.toString(16)+b.toString(16); return color; } var navo = '';//類目導航 var info = '';//商品內容 $.get('./results.json', function(data) {//請求json文件 $.each(data, function(index, val) { navo+="<a href='#"+val[0]+"''>"+val[0]+"</a> " });//把json文件中的類目數組遍歷出來,并用錨定位 $.each(data, function(index, val) { var div_title = "<div id='"+val[0]+"' style='float:left;'>"; var div_content = ""; $.each(val[1], function(index, val) { div_content+="<div style='background:"+color16()+"' onclick=\"location.href=\'"+val[21]+"\'\" class='pro_img'>"+val[1]+"<span class='money'>¥"+val[6]+"</span><\/div>" }); var div_footer ="</div><br>"; info+=div_title+div_content+div_footer }); $('#nav').html(navo);//把導航顯示出來 $('#content').html(info);//把商品顯示出來 },'json'); }) </script> <style> #content{ margin-top: 10px } .money{ position: absolute; left: 0; bottom: 0; height: 30px; line-height: 30px; color: #e22a40; font-weight: 700 } .pro_img{ position: relative; float: left; width: 220px; height: 220px; line-height: 220px; text-align: center; border: 1px solid #eee; cursor: pointer; font-size: 30px; white-space:normal; overflow:hidden; /*超過部分不顯示*/ text-overflow:ellipsis; /*超過部分用點點表示*/ white-space:nowrap;*//*不換行 } </style> </head> <body> <div id="nav"></div> <div id="content"></div> </body> </html>
https://fjxasdf.github.io/daogou (github比較卡)
信我或關注微信號:獅范兒,回復:學習,獲取免費學習資源包。
Excel文件轉成html頁面代碼
main類:啟動類
package com.test; import trans.toHtml; public class testToHtml { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub toHtml th=new toHtml(); // System.out.println(System.getProperty("java.library.path")); //-Djava.library.path=D:\jar\jacob_1.9 th.excelToHtml("d:/excel/運維門戶通訊錄.xlsx", "d:/test.html"); } }
代碼:
package trans; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import com.jacob.activeX.ActiveXComponent; import com.jacob.com.Dispatch; import com.jacob.com.Variant; public class toHtml { int WORD_HTML = 8; int WORD_TXT = 7; int EXCEL_HTML = 44; /** * WORD?HTML * @param docfile WORD ? ?· * @param htmlfile ? HTML · */ public void wordToHtml(String docfile, String htmlfile) { ActiveXComponent app = new ActiveXComponent("Word.Application"); // word try { app.setProperty("Visible", new Variant(false)); Dispatch docs = app.getProperty("Documents").toDispatch(); Dispatch doc = Dispatch.invoke(docs,"Open",Dispatch.Method,new Object[] { docfile, new Variant(false),new Variant(true) }, new int[1]).toDispatch(); Dispatch.invoke(doc, "SaveAs", Dispatch.Method, new Object[] {htmlfile, new Variant(WORD_HTML) }, new int[1]); Variant f = new Variant(false); Dispatch.call(doc, "Close", f); } catch (Exception e) { e.printStackTrace(); } finally { app.invoke("Quit", new Variant[] {}); } } /** * EXCEL?HTML * @param xlsfile EXCEL ? ?· * @param htmlfile ? HTML · */ public void excelToHtml(String xlsfile, String htmlfile) { ActiveXComponent app = new ActiveXComponent("Excel.Application"); // excel try { app.setProperty("Visible", new Variant(false)); Dispatch excels = app.getProperty("Workbooks").toDispatch(); Dispatch excel = Dispatch.invoke(excels,"Open",Dispatch.Method,new Object[] { xlsfile, new Variant(false),new Variant(true) }, new int[1]).toDispatch(); Dispatch.invoke(excel, "SaveAs", Dispatch.Method, new Object[] {htmlfile, new Variant(EXCEL_HTML) }, new int[1]); Variant f = new Variant(false); Dispatch.call(excel, "Close", f); } catch (Exception e) { e.printStackTrace(); } finally { app.invoke("Quit", new Variant[] {}); } } /** * /? ? * @param folderPath ? ?· * @param htmlfile ? HTML · */ public void delFolder(String folderPath) { try { delAllFile(folderPath); //? String filePath = folderPath; filePath = filePath.toString(); java.io.File myFilePath = new java.io.File(filePath); myFilePath.delete(); //? ? } catch (Exception e) {e.printStackTrace();} } /** * /? ? ? * @param path ? ?· */ public boolean delAllFile(String path) { boolean flag = false; File file = new File(path); if (!file.exists()) { return flag; } if (!file.isDirectory()) { return flag; } String[] tempList = file.list(); File temp = null; for (int i = 0; i < tempList.length; i++) { if (path.endsWith(File.separator)) { temp = new File(path + tempList[i]); } else { temp = new File(path + File.separator + tempList[i]); } if (temp.isFile()) { temp.delete(); } if (temp.isDirectory()) { delAllFile(path + "/" + tempList[i]);// ? ? ? delFolder(path + "/" + tempList[i]);// ? ? flag = true; } } return flag; } } 需要的jar包 <<jacob.jar>> <<toHtml.java>> <<testToHtml.java>>
來源網絡,侵權聯系刪除
私信我或關注微信號:獅范兒,回復:學習,獲取免費學習資源包。
能轉換:R圖和統計表轉成發表級的Word、PPT、Excel、HTML、Latex、矢量圖等
R包export可以輕松的將R繪制的圖和統計表輸出到 Microsoft Office (Word、PowerPoint和Excel)、HTML和Latex中,其質量可以直接用于發表。
export包可以在Windows、Ubuntu和Mac上跨平臺運行。不過有些Mac發行版默認情況下沒有安裝cairo設備,需要自行安裝。如果Mac用戶已安裝XQuartz,這個問題就解決了,它可以從https://www.xquartz.org/免費獲得。
install.packages("export")
install.packages("officer")
install.packages("rvg")
install.packages("openxlsx")
install.packages("ggplot2")
install.packages("flextable")
install.packages("xtable")
install.packages("rgl")
install.packages("stargazer")
install.packages("tikzDevice")
install.packages("xml2")
install.packages("broom")
install.packages("devtools")
devtools::install_github("tomwenseleers/export")
該包主要包括以下幾種轉換
使用幫助信息如下:
graph2bitmap(x = NULL, file = "Rplot", fun = NULL, type = c("PNG","JPG", "TIF"),
aspectr = NULL, width = NULL, height = NULL, dpi = 300,scaling = 100,
font =ifelse(Sys.info()["sysname"] == "Windows", "Arial",
"Helvetica")[[1]], bg = "white", cairo = TRUE,
tiffcompression = c("lzw", "rle", "jpeg", "zip", "lzw+p", "zip+p"),
jpegquality = 99, ...)
安裝完 export包后,先調用該包
library(export)
library(ggplot2)
library(datasets)
x=qplot(Sepal.Length, Petal.Length, data = iris,
color = Species, size = Petal.Width, alpha = I(0.7))
qplot()的意思是快速作圖,利用它可以很方便的創建各種復雜的圖形,其他系統需要好幾行代碼才能解決的問題,用qplot只需要一行就能完成。
使用半透明的顏色可以有效減少圖形元素重疊的現象,要創建半透明的顏色,可以使用alpha圖形屬性,其值從0(完全透明)到1(完全不透明)。更多ggplot2繪圖見ggplot2高效實用指南 (可視化腳本、工具、套路、配色) (往期教程更有很多生物信息相關的例子)。
鳶尾花(iris)是數據挖掘常用到的一個數據集,包含150個鳶尾花的信息,每50個取自三個鳶尾花種之一(setosa,versicolour或virginica)。每個花的特征用下面的5種屬性描述萼片長度(Sepal.Length)、萼片寬度(Sepal.Width)、花瓣長度(Petal.Length)、花瓣寬度(Petal.Width)、類(Species)。
在console里展示數據圖 (長寬比自己調節):
# 需運行上面的ggplot2繪圖
# Create a file name
# 程序會自動加后綴
filen <- "output_filename" # or
# filen <- paste("YOUR_DIR/ggplot")
# There are 3 ways to use graph2bitmap():
### 1. Pass the plot as an object
graph2png(x=x, file=filen, dpi=400, height = 5, aspectr=4)
graph2tif(x=x, file=filen, dpi=400, height = 5, aspectr=4)
graph2jpg(x=x, file=filen, dpi=400, height = 5, aspectr=4)
### 2. Get the plot from current screen device
# 注意這個x,是運行命令,展示圖像
x
graph2png(file=filen, dpi=400, height = 5, aspectr=4)
graph2tif(file=filen, dpi=400, height = 5, aspectr=4)
graph2jpg(file=filen, dpi=400, height = 5, aspectr=4)
### 3. Pass the plot as a functio
plot.fun <- function(){
print(qplot(Sepal.Length, Petal.Length, data = iris,
color = Species, size = Petal.Width, alpha = 0.7))
}
graph2png(file=filen, fun=plot.fun, dpi=400, height = 5, aspectr=4)
graph2tif(file=filen, fun=plot.fun, dpi=400, height = 5, aspectr=4)
graph2jpg(file=filen, fun=plot.fun, dpi=400, height = 5, aspectr=4)
轉換后的圖形:
大部分圖的細節修改都是用代碼完成的,不需要后續的修飾;但如果某一些修改比較特異,不具有程序的通用性特征,或實現起來比較困難,就可以考慮后期修改。比如用AI文章用圖的修改和排版。熟悉PPT的,也可以用PPT,這時R的圖導出PPT,就要用到graph2office系列函數了。
graph2ppt: 將當前R圖保存到Microsoft Office PowerPoint/LibreOffice Impress演示文稿中。
graph2doc:將當前的R圖保存到Microsoft Office Word/LibreOffice Writer文檔中。
函數參數展示和解釋
graph2office(x = NULL, file = "Rplot", fun = NULL, type = c("PPT", "DOC"),
append = FALSE, aspectr = NULL, width = NULL, height = NULL,scaling = 100,
paper = "auto", orient = ifelse(type[1] == "PPT","landscape", "auto"),
margins = c(top = 0.5, right = 0.5, bottom = 0.5, left= 0.5),
center = TRUE, offx = 1, offy = 1, upscale = FALSE, vector.graphic = TRUE, ...)
# 需運行上面的ggplot2繪圖
# Create a file name
filen <- "output_filename" # or
# filen <- paste("YOUR_DIR/ggplot")
# There are 3 ways to use graph2office():
### 1. Pass the plot as an object
# 導出圖形對象
graph2ppt(x=x, file=filen)
graph2doc(x=x, file=filen, aspectr=0.5)
### 2. Get the plot from current screen device
# 導出當前預覽窗口呈現的圖
x
graph2ppt(file=filen, width=9, aspectr=2, append = TRUE)
graph2doc(file=filen, aspectr=1.7, append =TRUE)
### 3. Pass the plot as a function
# 導出自定義函數輸出的一系列圖
graph2ppt(fun=plot.fun, file=filen, aspectr=0.5, append = TRUE)
graph2doc(fun=plot.fun, file=filen, aspectr=0.5, append = TRUE)
導出到office(ppt和word)中的圖形,是可編輯的:
其它導出到ppt的例子(設置長寬比)
graph2ppt(file="ggplot2_plot.pptx", aspectr=1.7)
增加第二張同樣的圖,9英寸寬和A4長寬比的幻燈片 (append=T,追加)
graph2ppt(file="ggplot2_plot.pptx", width=9, aspectr=sqrt(2), append=TRUE)
添加相同圖形的第三張幻燈片,寬度和高度固定
graph2ppt(file="ggplot2_plot.pptx", width=6, height=5, append=TRUE)
禁用矢量化圖像導出
graph2ppt(x=x, file=filen, vector.graphic=FALSE, width=9, aspectr=sqrt(2), append = TRUE)
用圖填滿幻燈片
graph2ppt(x=x, file=filen, margins=0, upscale=TRUE, append=TRUE)
函數參數解釋
graph2vector(x = NULL, file = "Rplot", fun = NULL, type = "SVG",aspectr = NULL,
width = NULL, height = NULL, scaling = 100,
font = ifelse(Sys.info()["sysname"] == "Windows",
"Arial","Helvetica")[[1]], bg = "white", colormodel = "rgb",
cairo = TRUE,fallback_resolution = 600, ...)
#需運行上面的ggplot2繪圖
# Create a file name
filen <- "output_filename" # or
# filen <- paste("YOUR_DIR/ggplot")
# There are 3 ways to use graph2vector():
### 1. Pass the plot as an object
# 導出圖形對象
graph2svg(x=x, file=filen, aspectr=2, font = "Times New Roman",
height = 5, bg = "white")
graph2pdf(x=x, file=filen, aspectr=2, font = "Arial",
height = 5, bg = "transparent")
graph2eps(x=x, file=filen, aspectr=2, font = "Arial",
height = 5, bg = "transparent")
# 導出當前預覽窗口呈現的圖
### 2. Get the plot from current screen device
x
graph2svg(file=filen, aspectr=2, font = "Arial",
height = 5, bg = "transparent")
graph2pdf(file=filen, aspectr=2, font = "Times New Roman",
height = 5, bg = "white")
graph2eps(file=filen, aspectr=2, font = "Times New Roman",
height = 5, bg = "white")
# 導出自定義函數輸出的一系列圖
### 3. Pass the plot as a function
graph2svg(file=filen, fun = plot.fun, aspectr=2, font = "Arial",
height = 5, bg = "transparent")
graph2pdf(file=filen, fun=plot.fun, aspectr=2, font = "Arial",
height = 5, bg = "transparent")
graph2eps(file=filen, fun=plot.fun, aspectr=2, font = "Arial",
height = 5, bg = "transparent")
rgl2png: 將當前的rgl 3D圖形保存為PNG格式。
rgl2bitmap(file = "Rplot", type = c("PNG"))
# Create a file name
filen <- tempfile("rgl") # or
# filen <- paste("YOUR_DIR/rgl")
# Generate a 3D plot using 'rgl'
x = y = seq(-10, 10, length = 20)
z = outer(x, y, function(x, y) x^2 + y^2)
rgl::persp3d(x, y, z, col = 'lightblue')
# Save the plot as a png
rgl2png(file = filen)
# Note that omitting 'file' will save in current directory
生成的3D圖形:
將生成的3D圖形保存為PNG格式:
table2spreadsheet(x = NULL, file = "Rtable", type = c("XLS", "CSV",
"CSV2"), append = FALSE, sheetName = "new sheet", digits = 2,
digitspvals = 2, trim.pval = TRUE, add.rownames = FALSE, ...)
# Create a file name
filen <- "table_aov" # or
# filen <- paste("YOUR_DIR/table_aov")
# Generate ANOVA output
fit=aov(yield ~ block + N * P + K, data = npk) # 'npk' dataset from base 'datasets'
x=summary(fit)
# Save ANOVA table as a CSV
### Option 1: pass output as object
# 輸出對象
table2csv(x=x,file=filen, digits = 1, digitspvals = 3, add.rownames=TRUE)
# 屏幕輸出導出到文件
### Option 2: get output from console
summary(fit)
table2csv(file=filen, digits = 2, digitspvals = 4, add.rownames=TRUE)
# Save ANOVA table as an Excel
# Without formatting of the worksheet
x
table2excel(file=filen, sheetName="aov_noformatting", digits = 1, digitspvals = 3, add.rownames=TRUE)
# 更多參數
# With formatting of the worksheet
table2excel(x=x,file=filen, sheetName="aov_formated", append = TRUE, add.rownames=TRUE, fontName="Arial", fontSize = 14, fontColour = rgb(0.15,0.3,0.75), border=c("top", "bottom"), fgFill = rgb(0.9,0.9,0.9), halign = "center", valign = "center", textDecoration="italic")
原始數據的表格:
轉換格式之后的,在console中的數據:
文件(csv和excel)中表格數據:
table2ppt: 導出統計輸出到Microsoft Office PowerPoint/ LibreOffice Impress演示文稿中的表
table2doc: 將統計輸出導出到Microsoft Office Word/ LibreOffice Writer文檔中的表
table2office(x = NULL, file = "Rtable", type = c("PPT", "DOC"),
append = FALSE, digits = 2, digitspvals = 2, trim.pval = TRUE,
width = NULL, height = NULL, offx = 1, offy = 1,
font = ifelse(Sys.info()["sysname"] == "Windows", "Arial",
"Helvetica")[[1]], pointsize = 12, add.rownames = FALSE)
# Create a file name
filen <- "table_aov"
# filen <- paste("YOUR_DIR/table_aov")
# Generate ANOVA output
fit=aov(yield ~ block + N * P + K, data = npk) # 'npk' dataset from base 'datasets'
# Save ANOVA table as a PPT
### Option 1: pass output as object
x=summary(fit)
table2ppt(x=x,file=filen, digits = 1, digitspvals = 3, add.rownames =TRUE)
### Option 2: get output from console
summary(fit)
table2ppt(x=x,file=filen, width=5, font="Times New Roman", pointsize=14, digits=4, digitspvals=1, append=TRUE, add.rownames =TRUE) # append table to previous slide
# Save ANOVA table as a DOC file
table2doc(x=x,file=filen, digits = 1, digitspvals = 3, add.rownames =TRUE)
summary(fit)
table2doc(file=filen, width=3.5, font="Times New Roman", pointsize=14, digits=4, digitspvals=1, append=TRUE, add.rownames =TRUE) # append table at end of document
將表格數據導出到ppt和word中:
table2html: 導出統計輸出到HTML表。
table2tex(x = NULL, file = "Rtable", type = "TEX", digits = 2,
digitspvals = 2, trim.pval = TRUE, summary = FALSE, standAlone = TRUE,
add.rownames = FALSE, ...)
summary:是否匯總數據文件。
standAlone:導出的Latex代碼應該是獨立可編譯的,還是應該粘貼到另一個文檔中。
add.rownames:是否應該將行名添加到表中(在第一列之前插入一列)。
# Create a file name
filen <- tempfile(pattern = "table_aov") # or
# filen <- paste("YOUR_DIR/table_aov")
# Generate ANOVA output
fit=aov(yield ~ block + N * P + K, data = npk) # 'npk' dataset from base 'datasets'
x=summary(fit)
# Export to Latex in standAlone format
table2tex(x=x,file=filen,add.rownames = TRUE)
# Export to Latex to paste in tex document
summary(fit) # get output from the console
table2tex(file=filen, standAlone = FALSE,add.rownames = TRUE)
# Export to HTML
table2html(x=x,file=filen) # or
summary(fit) # get output from the console
table2html(file=filen,add.rownames = TRUE)
導出到html或tex中的表格數據:
*請認真填寫需求信息,我們會在24小時內與您取得聯系。