⚡ Tabular Data & File Management in Gradio
Gradio provides robust components for handling spreadsheets and documents. gr.Dataframe acts as an interactive spreadsheet grid for viewing and editing pandas DataFrames, while gr.File enables seamless document uploading and downloadable file generation.
Example 1: Interactive Dataframe Viewer & Editor (`gr.Dataframe`)
Displays a spreadsheet data grid allowing users to inspect and edit table rows and columns.
Python (df_ex1.py)
import gradio as gr
import pandas as pd
initial_df = pd.DataFrame({
"Product": ["Laptop", "Mouse", "Keyboard"],
"Price ($)": [1200, 25, 75],
"Stock": [15, 120, 50]
})
def process_table(df):
return f"Total Inventory Valuation: $ {(df['Price ($)'] * df['Stock']).sum():,}"
demo = gr.Interface(
fn=process_table,
inputs=gr.Dataframe(value=initial_df, label="Inventory Spreadsheet"),
outputs=gr.Textbox(label="Calculation Result"),
title="Interactive Spreadsheet Processor"
)
if __name__ == "__main__":
demo.launch()
🖥️ Live Web UI Visual Output Preview
### Interactive Spreadsheet Processor
[Interactive Grid Table: Product | Price ($) | Stock]
Total Inventory Valuation: $ 21,750
Example 2: CSV Dataset Uploader & Column Sorter
Accepts uploaded CSV files, reads them into pandas, and sorts records based on target columns.
Python (df_ex2.py)
import gradio as gr
import pandas as pd
def sort_csv(file, sort_col):
if file is None:
return pd.DataFrame()
df = pd.read_csv(file.name)
if sort_col in df.columns:
df = df.sort_values(by=sort_col, ascending=False)
return df
demo = gr.Interface(
fn=sort_csv,
inputs=[gr.File(label="Upload CSV Dataset"), gr.Textbox(label="Sort Column Name", value="id")],
outputs=gr.Dataframe(label="Sorted Data Grid"),
title="CSV Dataset Sorter"
)
if __name__ == "__main__":
demo.launch()
🖥️ Live Web UI Visual Output Preview
### CSV Dataset Sorter
Upload CSV Dataset Drop Zone
Sort Column Name: id
[Sorted Dataframe Table Grid]
Example 3: Downloadable CSV Report Generator (`gr.File` Output)
Generates a CSV report file programmatically and returns it as a downloadable file widget.
Python (df_ex3.py)
import gradio as gr
import pandas as pd
def generate_report(prefix):
df = pd.DataFrame({"Code": [101, 102], "Item": [f"{prefix}_Alpha", f"{prefix}_Beta"], "Value": [500, 750]})
file_path = "/tmp/generated_report.csv"
df.to_csv(file_path, index=False)
return file_path
demo = gr.Interface(
fn=generate_report,
inputs=gr.Textbox(label="Report Prefix", value="Nikita"),
outputs=gr.File(label="Download Report File"),
title="Automated CSV Report Builder"
)
if __name__ == "__main__":
demo.launch()
🖥️ Live Web UI Visual Output Preview
### Automated CSV Report Builder
Report Prefix: Nikita
📁 generated_report.csv (Ready for Download)
Example 4: Text File Word & Line Counter
Parses uploaded text files to calculate exact word counts, line counts, and character statistics.
Python (df_ex4.py)
import gradio as gr
def analyze_text_file(file):
if file is None:
return "No file uploaded."
with open(file.name, "r", encoding="utf-8") as f:
content = f.read()
lines = content.splitlines()
words = content.split()
return f"Lines: {len(lines)} | Words: {len(words)} | Characters: {len(content)}"
demo = gr.Interface(
fn=analyze_text_file,
inputs=gr.File(label="Upload Text Document (.txt)"),
outputs=gr.Textbox(label="Document Statistics"),
title="Text Document Analyzer"
)
if __name__ == "__main__":
demo.launch()
🖥️ Live Web UI Visual Output Preview
### Text Document Analyzer
Upload Text Document (.txt) Drop Zone
Lines: 42 | Words: 380 | Characters: 2,450
Example 5: JSON Data Viewer & Inspector (`gr.JSON`)
Uploads JSON configuration files and displays parsed key-value structures cleanly.
Python (df_ex5.py)
import gradio as gr
import json
def parse_json_file(file):
if file is None:
return {"error": "No file uploaded"}
with open(file.name, "r") as f:
data = json.load(f)
return data
demo = gr.Interface(
fn=parse_json_file,
inputs=gr.File(label="Upload JSON Config"),
outputs=gr.JSON(label="Parsed JSON Viewer"),
title="JSON File Inspector"
)
if __name__ == "__main__":
demo.launch()
🖥️ Live Web UI Visual Output Preview
### JSON File Inspector
Upload JSON Config Drop Zone
{ "status": "success", "app": "Nikita-Infotech" }
Example 6: Spreadsheet Summary Statistics Calculator
Computes mathematical summary metrics (mean, min, max, std) from numerical spreadsheet columns.
Python (df_ex6.py)
import gradio as gr
import pandas as pd
def get_stats(file):
if file is None:
return pd.DataFrame()
df = pd.read_csv(file.name)
return df.describe()
demo = gr.Interface(
fn=get_stats,
inputs=gr.File(label="Upload CSV Spreadsheet"),
outputs=gr.Dataframe(label="Statistical Summary Grid"),
title="Spreadsheet Statistics Calculator"
)
if __name__ == "__main__":
demo.launch()
🖥️ Live Web UI Visual Output Preview
### Spreadsheet Statistics Calculator
Upload CSV Spreadsheet Drop Zone
[Pandas describe() Statistical Table Grid]
Example 7: Multi-File Batch Archive Generator (`zipfile`)
Accepts multiple uploaded files, packages them into a single ZIP archive, and provides a download link.
Python (df_ex7.py)
import gradio as gr
import zipfile
import os
def create_zip(files):
if not files:
return None
zip_path = "/tmp/batch_archive.zip"
with zipfile.ZipFile(zip_path, 'w') as zf:
for file in files:
zf.write(file.name, arcname=os.path.basename(file.name))
return zip_path
demo = gr.Interface(
fn=create_zip,
inputs=gr.File(file_count="multiple", label="Upload Multiple Files"),
outputs=gr.File(label="Download ZIP Archive"),
title="Batch File ZIP Packager"
)
if __name__ == "__main__":
demo.launch()
🖥️ Live Web UI Visual Output Preview
### Batch File ZIP Packager
Upload Multiple Files Drop Zone
📁 batch_archive.zip (Ready to Download)
Example 8: CSV Data Filter & Search Query Tool
Searches and filters rows in a dataset matching user-provided keyword queries.
Python (df_ex8.py)
import gradio as gr
import pandas as pd
def search_csv(file, keyword):
if file is None or not keyword:
return pd.DataFrame()
df = pd.read_csv(file.name)
mask = df.astype(str).apply(lambda col: col.str.contains(keyword, case=False)).any(axis=1)
return df[mask]
demo = gr.Interface(
fn=search_csv,
inputs=[gr.File(label="Upload CSV"), gr.Textbox(label="Search Keyword", value="Nikita")],
outputs=gr.Dataframe(label="Matching Records"),
title="Dataset Keyword Search Tool"
)
if __name__ == "__main__":
demo.launch()
🖥️ Live Web UI Visual Output Preview
### Dataset Keyword Search Tool
Upload CSV Drop Zone
Search Keyword: Nikita
[Filtered Matching Records Grid]
Example 9: Excel / CSV Format Converter Tool
Converts uploaded CSV datasets into downloadable Excel spreadsheets or vice-versa.
Python (df_ex9.py)
import gradio as gr
import pandas as pd
def convert_format(file):
if file is None:
return None
df = pd.read_csv(file.name)
out_path = "/tmp/converted_spreadsheet.xlsx"
df.to_excel(out_path, index=False)
return out_path
demo = gr.Interface(
fn=convert_format,
inputs=gr.File(label="Upload CSV File"),
outputs=gr.File(label="Download Excel File (.xlsx)"),
title="CSV to Excel Format Converter"
)
if __name__ == "__main__":
demo.launch()
🖥️ Live Web UI Visual Output Preview
### CSV to Excel Format Converter
Upload CSV File Drop Zone
📁 converted_spreadsheet.xlsx (Ready to Download)
Example 10: Enterprise Data Management & Analytics Hub (`gr.Blocks`)
Combines spreadsheet data grids, file upload widgets, and summary metrics into an enterprise dashboard.
Python (df_ex10.py)
import gradio as gr
import pandas as pd
def load_data(file):
if file is None:
return pd.DataFrame(), "No file loaded."
df = pd.read_csv(file.name)
summary = f"Loaded {len(df)} rows and {len(df.columns)} columns successfully."
return df, summary
with gr.Blocks() as demo:
gr.Markdown("# 📊 Enterprise Data Management Hub")
with gr.Row():
f_in = gr.File(label="Upload Dataset (CSV)")
status = gr.Textbox(label="System Status")
grid = gr.Dataframe(label="Interactive Dataset Table")
f_in.upload(load_data, inputs=f_in, outputs=[grid, status])
if __name__ == "__main__":
demo.launch()
🖥️ Live Web UI Visual Output Preview
# 📊 Enterprise Data Management Hub
Upload Dataset Drop Zone
Loaded 150 rows and 5 columns successfully.
[Interactive Dataframe Spreadsheet Grid View]