csv到html表可能吗?

问题描述 投票:0回答:1

我有一个充满日历信息的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 out put看起来像这样:

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

使用pivot来移动日期:

data = data.pivot(index='Employee', columns = 'Start', values='Task').reset_index()
python html csv html-table
1个回答
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文件“input.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>
© www.soinside.com 2019 - 2024. All rights reserved.