Python實(shí)現(xiàn)Excel表格數(shù)據(jù)讀取及轉(zhuǎn)換保存
Python代碼實(shí)現(xiàn)選擇打開.xls以及.xlsx類型的表格文件,在文本框中顯示表格數(shù)據(jù),也可以在文本框中粘貼或者編輯數(shù)據(jù),選擇導(dǎo)出.txt文本文件或者.xlsx表格文件。
(本代碼暫不支持導(dǎo)出.xls格式文件)
一、效果圖預(yù)覽

表格數(shù)據(jù)隨機(jī)生成如下所示:

二、代碼運(yùn)行報(bào)錯(cuò)處理(pip install )
如果運(yùn)行報(bào)錯(cuò),可能是沒有導(dǎo)入pandas庫的原因,可以win+r進(jìn)入運(yùn)行界面,輸入pip install pandas,導(dǎo)入pandas庫即可。
同理如果有其他庫缺失報(bào)錯(cuò),同樣可以(pip install 庫名)運(yùn)行導(dǎo)入。
三、代碼演示
借助AI生成主體代碼后,進(jìn)行優(yōu)化調(diào)整后代碼如下:
#Python代碼,tkinter界面,選擇打開xls表格文件,讀取表格數(shù)據(jù),在text中顯示出來,可導(dǎo)出為文本文件
#pip install pandas
import tkinter as tk
from tkinter import filedialog, messagebox
import pandas as pd
class ExcelToTextApp:
def __init__(self, root):
self.root = root
self.root.title("Excel to Text Converter")
# Create widgets
self.create_widgets()
def create_widgets(self):
# Button to open Excel file
self.open_button = tk.Button(self.root, text="Open Excel File", command=self.open_file)
self.open_button.pack(pady=10)
# Text widget to display data
self.text = tk.Text(self.root, height=20, width=80)
self.text.pack(pady=10)
# Button to export text
self.export_button = tk.Button(self.root, text="Export to Text File", command=self.export_text)
self.export_button.pack(pady=10)
# Button to export to Excel
self.excel_export_button = tk.Button(self.root, text="Export to Excel", command=self.export_excel)
self.excel_export_button.pack(pady=10)
def open_file(self):
file_path = filedialog.askopenfilename(filetypes=[("Excel files", "*.xls;*.xlsx")])
if file_path:
try:
df = pd.read_excel(file_path)
# Convert DataFrame to string representation
excel_data = df.to_string()
self.text.delete(1.0, tk.END) # Clear previous data
self.text.insert(tk.END, excel_data) # Insert new data
except Exception as e:
messagebox.showerror("Error", f"Failed to read Excel file: {e}")
def export_text(self):
file_path = filedialog.asksaveasfilename(defaultextension=".txt", filetypes=[("Text files", "*.txt")])
if file_path:
try:
with open(file_path, 'w', encoding='utf-8') as f:
f.write(self.text.get(1.0, tk.END))
messagebox.showinfo("Success", "Data exported successfully!")
except Exception as e:
messagebox.showerror("Error", f"Failed to export data: {e}")
def export_excel(self):
# Get text content
text_content = self.text.get(1.0, tk.END)
# Check if content is empty
if not text_content.strip():
messagebox.showerror("Error", "No data to export")
return
# Try to convert text to DataFrame
try:
# Split text into lines
lines = text_content.strip().split('\n')
# Extract column names (first line)
columns = lines[0].split()
# Prepare data rows
data = []
for line in lines[1:]:
# Split each line into columns
row_data = line.split()
# Handle rows with different number of columns
if len(row_data) != len(columns):
# Pad with empty strings if too short
row_data += [''] * (len(columns) - len(row_data))
# Truncate if too long
row_data = row_data[:len(columns)]
data.append(row_data)
# Create DataFrame
df = pd.DataFrame(data, columns=columns)
# Ask for save location
file_path = filedialog.asksaveasfilename(
defaultextension=".xlsx",
filetypes=[("Excel files", "*.xlsx")],
title="Save as Excel file"
)
if file_path:
try:
# Save to Excel
df.to_excel(file_path, index=False)
messagebox.showinfo("Success", "Data exported successfully!")
except Exception as e:
messagebox.showerror("Error", f"Failed to export Excel file: {e}")
except Exception as e:
messagebox.showerror("Error", f"Failed to convert text to Excel format: {e}")
if __name__ == "__main__":
root = tk.Tk()
app = ExcelToTextApp(root)
root.mainloop()四、知識(shí)擴(kuò)展
Python 讀取和轉(zhuǎn)換 Excel 數(shù)據(jù)最常用的庫是 pandas(配合 openpyxl 或 xlrd 引擎)。pandas 提供強(qiáng)大的數(shù)據(jù)處理能力,可以輕松完成篩選、計(jì)算、分組、合并等轉(zhuǎn)換操作。
1. 環(huán)境準(zhǔn)備
安裝必要的庫:
pip install pandas openpyxl
pandas:核心數(shù)據(jù)處理庫。openpyxl:讀取/寫入.xlsx文件引擎。
2. 讀取 Excel 數(shù)據(jù)
基本讀取
import pandas as pd
# 讀取整個(gè) Excel 文件的第一個(gè)工作表
df = pd.read_excel('data.xlsx')
print(df.head()) # 查看前5行指定工作表
# 按工作表名稱
df = pd.read_excel('data.xlsx', sheet_name='Sheet1')
# 按工作表索引 (0 表示第一個(gè))
df = pd.read_excel('data.xlsx', sheet_name=0)
# 讀取多個(gè)工作表,返回字典
dfs = pd.read_excel('data.xlsx', sheet_name=['Sheet1', 'Sheet2'])指定列與行
# 只讀取 A,C,D 列 (A=0, B=1, C=2, D=3, ...)
df = pd.read_excel('data.xlsx', usecols='A,C,D')
# 或使用列名列表
df = pd.read_excel('data.xlsx', usecols=['Name', 'Age', 'Salary'])
# 跳過前2行,以第3行為表頭
df = pd.read_excel('data.xlsx', skiprows=2, header=0)
# 讀取特定行范圍(例如前100行)
df = pd.read_excel('data.xlsx', nrows=100)處理數(shù)據(jù)類型
# 指定列的數(shù)據(jù)類型,避免自動(dòng)推斷出錯(cuò)
dtype = {'ID': str, 'Age': int}
df = pd.read_excel('data.xlsx', dtype=dtype)3. 數(shù)據(jù)轉(zhuǎn)換常用操作
查看與清洗
# 查看基本信息
df.info()
df.describe()
# 檢查缺失值
df.isnull().sum()
# 刪除包含缺失值的行
df_clean = df.dropna()
# 填充缺失值
df['Age'] = df['Age'].fillna(df['Age'].median())
df['Note'] = df['Note'].fillna('暫無')列操作(新增、修改、刪除)
# 新增列(計(jì)算)
df['Total'] = df['Price'] * df['Quantity']
# 修改列名
df.rename(columns={'OldName': 'NewName'}, inplace=True)
# 刪除列
df.drop(['Unnamed: 0', 'TempCol'], axis=1, inplace=True)條件篩選
# 篩選 Age > 30 的行
df_filtered = df[df['Age'] > 30]
# 多條件(且)
df_filtered = df[(df['Age'] > 30) & (df['Salary'] < 5000)]
# 多條件(或)
df_filtered = df[(df['City'] == 'Beijing') | (df['City'] == 'Shanghai')]
# 按文本包含篩選
df_filtered = df[df['Name'].str.contains('張', na=False)]排序與去重
# 按一列排序
df_sorted = df.sort_values('Date', ascending=True)
# 按多列排序
df_sorted = df.sort_values(['Group', 'Value'], ascending=[True, False])
# 去重(保留第一個(gè))
df_unique = df.drop_duplicates(subset='ID')分組聚合
# 按部門統(tǒng)計(jì)平均工資
grouped = df.groupby('Department')['Salary'].mean().reset_index()
# 多聚合函數(shù)
result = df.groupby('Department').agg(
平均工資=('Salary', 'mean'),
最高工資=('Salary', 'max'),
人數(shù)=('EmployeeID', 'count')
).reset_index()數(shù)據(jù)類型轉(zhuǎn)換
# 將字符串日期轉(zhuǎn)為 datetime 類型
df['Date'] = pd.to_datetime(df['Date'], format='%Y-%m-%d')
# 將分類數(shù)據(jù)轉(zhuǎn)為 category 類型(節(jié)省內(nèi)存)
df['Status'] = df['Status'].astype('category')
# 數(shù)值列四舍五入
df['Rate'] = df['Rate'].round(2)4. 輸出轉(zhuǎn)換后的 Excel
# 保存到新文件,不包含行索引
df_result.to_excel('output.xlsx', index=False)
# 指定工作表名稱
df_result.to_excel('output.xlsx', sheet_name='轉(zhuǎn)換結(jié)果', index=False)
# 保存多個(gè)工作表到同一個(gè)文件
with pd.ExcelWriter('multi_sheet.xlsx') as writer:
df1.to_excel(writer, sheet_name='Sheet1', index=False)
df2.to_excel(writer, sheet_name='Sheet2', index=False)5. 完整示例:銷售數(shù)據(jù)轉(zhuǎn)換
假設(shè)有一個(gè)銷售記錄表 sales.xlsx,包含列:OrderID, Product, Category, Sales, Quantity, Date。
任務(wù):計(jì)算每筆訂單的 Revenue,并按 Category 統(tǒng)計(jì)總銷售額,最后輸出新文件。
import pandas as pd
# 1. 讀取數(shù)據(jù)
df = pd.read_excel('sales.xlsx')
# 2. 數(shù)據(jù)清洗:檢查缺失,刪除無訂單號(hào)的記錄
df.dropna(subset=['OrderID'], inplace=True)
# 3. 新增列:銷售額 = Sales * Quantity
df['Revenue'] = df['Sales'] * df['Quantity']
# 4. 將 Date 轉(zhuǎn)為日期類型
df['Date'] = pd.to_datetime(df['Date'])
# 5. 篩選:只保留 2025 年后的數(shù)據(jù)
df = df[df['Date'] >= '2025-01-01']
# 6. 分類匯總:按 Category 計(jì)算總 Revenue
category_summary = df.groupby('Category')['Revenue'].sum().reset_index()
category_summary.rename(columns={'Revenue': 'TotalRevenue'}, inplace=True)
# 7. 輸出結(jié)果到 Excel
with pd.ExcelWriter('sales_report.xlsx') as writer:
df.to_excel(writer, sheet_name='明細(xì)', index=False)
category_summary.to_excel(writer, sheet_name='分類匯總', index=False)
print("處理完成,已生成 sales_report.xlsx")到此這篇關(guān)于Python實(shí)現(xiàn)Excel表格數(shù)據(jù)讀取及轉(zhuǎn)換保存的文章就介紹到這了,更多相關(guān)Python Excel表格數(shù)據(jù)轉(zhuǎn)換內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- 使用Python和Spire.XLS輕松實(shí)現(xiàn)Excel到TXT數(shù)據(jù)轉(zhuǎn)換
- Python高效實(shí)現(xiàn)CSV數(shù)據(jù)轉(zhuǎn)換為規(guī)范的Excel文件
- Python實(shí)現(xiàn)Excel與TXT文本文件數(shù)據(jù)轉(zhuǎn)換的完整指南
- 使用Python將JSON格式的假期數(shù)據(jù)轉(zhuǎn)換為Excel文件
- Python高效實(shí)現(xiàn)Excel與TXT文本文件之間的數(shù)據(jù)轉(zhuǎn)換
- python?pdfplumber庫批量提取pdf表格數(shù)據(jù)轉(zhuǎn)換為excel
- 基于python實(shí)現(xiàn)把json數(shù)據(jù)轉(zhuǎn)換成Excel表格
相關(guān)文章
Python2與python3中 for 循環(huán)語句基礎(chǔ)與實(shí)例分析
Python for循環(huán)可以遍歷任何序列的項(xiàng)目,如一個(gè)列表或者一個(gè)字符串,也是python中比較常用的一個(gè)函數(shù),這里通過基礎(chǔ)與實(shí)例給大家分享一下2017-11-11
使用Python給Excel工作表設(shè)置背景色或背景圖
Excel是工作中數(shù)據(jù)處理和分析數(shù)據(jù)的重要工具,面對(duì)海量的數(shù)據(jù)和復(fù)雜的表格,如何提高工作效率、減少視覺疲勞并提升數(shù)據(jù)的可讀性是不容忽視的問題,而給工作表設(shè)置合適的背景是表格優(yōu)化的一個(gè)有效方式,本文將介紹如何用Python給Excel工作表設(shè)置背景色或背景圖2024-07-07
Python中kwargs.get()方法語法及高級(jí)用法詳解
這篇文章主要介紹了Python中kwargs.get()方法語法及高級(jí)用法的相關(guān)資料,該方法用于安全地獲取字典中的值,并提供了默認(rèn)值以避免KeyError異常,需要的朋友可以參考下2026-01-01
Python編寫繪圖系統(tǒng)之從文本文件導(dǎo)入數(shù)據(jù)并繪圖
這篇文章主要為大家詳細(xì)介紹了Python如何編寫一個(gè)繪圖系統(tǒng),可以實(shí)現(xiàn)從文本文件導(dǎo)入數(shù)據(jù)并繪圖,文中的示例代碼講解詳細(xì),感興趣的可以了解一下2023-08-08
python如何獲取Prometheus監(jiān)控?cái)?shù)據(jù)
這篇文章主要介紹了python如何獲取Prometheus監(jiān)控?cái)?shù)據(jù),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-05-05
如何在python中實(shí)現(xiàn)隨機(jī)選擇
這篇文章主要介紹了如何在python中實(shí)現(xiàn)隨機(jī)選擇,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2019-11-11
Python?from?import導(dǎo)包ModuleNotFoundError?No?module?named
最近在執(zhí)行python腳本時(shí),from?import的模塊沒有被加載進(jìn)來,找不到module,這篇文章主要給大家介紹了關(guān)于Python?from?import導(dǎo)包ModuleNotFoundError?No?module?named找不到模塊問題的解決辦法,需要的朋友可以參考下2022-08-08
關(guān)于Numpy之repeat、tile的用法總結(jié)
這篇文章主要介紹了關(guān)于Numpy之repeat、tile的用法總結(jié),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-06-06

