CSV到HTML表可能吗?

时间:2019-03-15 15:48:55

标签: python html csv html-table

我有一个充满日历信息的csv文件(calendar-data.csv) 我需要将其发布到网页上(或为其生成html)

我想要的是在表中(在“开始”列中)运行日期,然后在左侧运行员工姓名。在每个日期框中填写相应的任务

因此它看起来像:

             03/15/2019    03/16/2019

employee1      task            task 
                               task

employee2      task
               task

这段代码为我提供了html,但它是网页上的所有blob:

import csv
import sys

if len(sys.argv) < 2:
  print "Usage: ./csv-html.py <your CSV file> <your HTML File.html>"
  print
  print
  exit(0)

# Open the CSV file for reading
reader = csv.reader(open(sys.argv[1]))

# Create the HTML file
f_html = open(sys.argv[2],"w");
f_html.write('<title><Work Flow></title>')

for row in reader: # Read a single row from the CSV file
  f_html.write('<tr>');# Create a new row in the table
  for column in row: # For each column..
    f_html.write('<td>' + column + '</td>');
  f_html.write('</tr>')


f_html.write('</table>')

这可能在python中出现还是应该在其他地方查看?

谢谢

编辑:

现在html输出看起来像这样:

employee1 03/15/2019    tasks
employee1  03/15/2019   tasks
employee2  03/15/2019   tasks
employee2  03/16/2019   tasks

但是我希望它看起来像这样:

            03/15/2019           03/16/2019            03/17/2019

employee1      tasks               tasks
employee2      task                tasks
employee3                                                tasks

编辑2

使用枢轴移动日期:

data = data.pivot(index='Employee', columns = 'Start', values='Task').reset_index()

1 个答案:

答案 0 :(得分:2)

您可以使用pandas.read_csv将CSV文件读入pandas DataFrame中,然后使用pandas.to_html转换为html

对于CSV文件“ input.csv”

employee_name, 03/15/2019,03/16/2019
employee1, task1,task2 
employee2, task3, task4

我们可以将CSV文件作为DataFrame读取

import pandas as pd
df = pd.read_csv("input.csv", index_col="employee_name")

df是

               03/15/2019 03/16/2019
employee_name
employee1           task1     task2
employee2           task3      task4

然后我们可以使用以下方式将DataFrame转换为HTML表

df.to_html("input.html")

HTML文件“ intput.html”的输出将为

<table border="1" class="dataframe">
  <thead>
    <tr style="text-align: right;">
      <th></th>
      <th>03/15/2019</th>
      <th>03/16/2019</th>
    </tr>
    <tr>
      <th>employee_name</th>
      <th></th>
      <th></th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>employee1</th>
      <td>task1</td>
      <td>task2</td>
    </tr>
    <tr>
      <th>employee2</th>
      <td>task3</td>
      <td>task4</td>
    </tr>
  </tbody>
</table>