首页 > 解决方案 > csv到html表可能吗?

问题描述

我有一个包含日历信息的 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()

标签: pythonhtmlcsvhtml-table

解决方案


您可以使用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>


推荐阅读