将CSV转换为HTML表格格式并存储在HTML文件中 [英] Convert CSV to a HTML table format and store in a HTML file
本文介绍了将CSV转换为HTML表格格式并存储在HTML文件中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我尝试了一些Shell脚本将其转换为HTML表格格式,但没有得到所需的输出.任何人都可以在这里帮助您使用Python或PowerShell将CSV转换为HTML表格格式并将其存储到HTML文件中.
I have tried few shell scripts to convert to a HTML table format but I didnt get desired output. Could anyone help here to convert CSV to a HTML table format using Python or PowerShell and store it into HTML file.
推荐答案
这可能会帮助您:
import sys
import csv
if len(sys.argv) < 3:
print "Usage: csvToTable.py csv_file html_file"
exit(1)
# Open the CSV file for reading
reader = csv.reader(open(sys.argv[1]))
# Create the HTML file for output
htmlfile = open(sys.argv[2],"w")
# initialize rownum variable
rownum = 0
# write <table> tag
htmlfile.write('<table>')
# generate table contents
for row in reader: # Read a single row from the CSV file
# write header row. assumes first row in csv contains header
if rownum == 0:
htmlfile.write('<tr>') # write <tr> tag
for column in row:
htmlfile.write('<th>' + column + '</th>')
htmlfile.write('</tr>')
#write all other rows
else:
htmlfile.write('<tr>')
for column in row:
htmlfile.write('<td>' + column + '</td>')
htmlfile.write('</tr>')
#increment row count
rownum += 1
# write </table> tag
htmlfile.write('</table>')
# print results to shell
print "Created " + str(rownum) + " row table."
exit(0)
这篇关于将CSV转换为HTML表格格式并存储在HTML文件中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文