csv to html Converter. csv to datatables Converter.
This quick algorithm can convert CSV to html tables for quick publications to blogs and back end html inserters.
- Save your time. This simple conversion algorithm will convert csv to html!
- The next set of algorthims will convert it for datatables viewing!
import pandas as pd
import re
# Read the CSV file without headers and assign column names
df = pd.read_csv('posts.csv', header=None, names=['title', 'slug'])
# Function to extract number and file format from the title
def extract_info(title):
# Match patterns like "Task XXX: ...", "Task XXX - ...", "Test XXX: ..."
match = re.match(r'(Task|Test)\s+(\d+)[ :\-.]+(.*)', title.strip())
if match:
return match.group(2), match.group(3).strip()
else:
return '', title.strip()
# Apply the extraction function to create new columns
df[['number', 'file_format']] = df['title'].apply(lambda x: pd.Series(extract_info(x)))
# Create the HTML link column
df['html_link'] = df.apply(lambda row: f'<a href="{row["slug"]}">{row["file_format"]}</a>', axis=1)
# Select the relevant columns for the table
table_df = df[['number', 'file_format', 'html_link']]
# Generate the base HTML table
html_table = table_df.to_html(escape=False, index=False, header=['Number', 'File Format', 'HTML Link'])
# Add style to center the first column
# We replace the default <th> tags with styled ones
styled_html = html_table.replace(
'<thead>\n<tr>',
'<thead>\n<tr style="text-align: center;">'
)
# Optional: also center the number cells in the body (for consistency)
# This will center all <td> in the first column
styled_html = styled_html.replace(
'<td>',
'<td style="text-align: center;">',
1 # Only replace the first occurrence (header) — then we handle body separately
)
# Better approach: add a class or inline style only to the first column
# We'll insert style for the first <td> in each row
# A simple way is to use CSS (recommended) or inline styles
# Alternative: wrap the table in a div with CSS
final_html = f"""
<style>
table {{ border-collapse: collapse; width: 100%; }}
th, td {{ padding: 8px; border: 1px solid #ddd; }}
th:nth-child(1), td:nth-child(1) {{ text-align: center; }}
</style>
{final_html}
"""
print(final_html)If you need more powerful types of data viewing: Consider datatables.
csv to datatables converter
- The entire thing was extremely simple. Wow.
import pandas as pd
def csv_to_datatables_html(csv_file_path, table_id='example', classes='display'):
"""
Converts a CSV file to an HTML snippet suitable for insertion into a webpage,
formatted for use with DataTables jQuery plugin. Assumes the webpage includes
necessary DataTables libraries (CSS and JS).
Parameters:
- csv_file_path (str): Path to the input CSV file.
- table_id (str): ID for the HTML table element (default: 'example').
- classes (str): CSS classes for the table (default: 'display' for DataTables).
Returns:
- str: HTML string containing the table and DataTables initialization script.
"""
# Read the CSV file into a DataFrame
df = pd.read_csv(csv_file_path)
# Generate the HTML table from the DataFrame
html_table = df.to_html(table_id=table_id, classes=classes, index=False, escape=False)
# DataTables initialization script
init_script = f"""
<script>
document.addEventListener('DOMContentLoaded', function() {{
new DataTable('#{table_id}');
}});
</script>
"""
# Combine and return the HTML
return html_table + init_scriptAs a class format it will come out as:
import pandas as pd
class CSVToDataTablesHTML:
"""
A class to convert a CSV file to an HTML snippet formatted for use with the DataTables jQuery plugin.
It generates the HTML table and initialization script, and provides a method to save the output to a file.
Assumes the webpage includes necessary DataTables libraries (CSS and JS).
Attributes:
- csv_file_path (str): Path to the input CSV file.
- table_id (str): ID for the HTML table element (default: 'example').
- classes (str): CSS classes for the table (default: 'display' for DataTables).
"""
def __init__(self, csv_file_path, table_id='example', classes='display'):
self.csv_file_path = csv_file_path
self.table_id = table_id
self.classes = classes
def generate_html(self):
"""
Generates the HTML string containing the table and DataTables initialization script.
Returns:
- str: The generated HTML string.
"""
# Read the CSV file into a DataFrame
df = pd.read_csv(self.csv_file_path)
# Generate the HTML table from the DataFrame
html_table = df.to_html(table_id=self.table_id, classes=self.classes, index=False, escape=False)
# DataTables initialization script
init_script = f"""
<script>
document.addEventListener('DOMContentLoaded', function() {{
new DataTable('#{self.table_id}');
}});
</script>
"""
# Combine and return the HTML
return html_table + init_script
def save_to_file(self, output_path):
"""
Generates the HTML and saves it to the specified file path.
Parameters:
- output_path (str): The path where the HTML file will be saved.
"""
html = self.generate_html()
with open(output_path, 'w', encoding='utf-8') as file:
file.write(html)