最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python實現(xiàn)Excel表格數(shù)據(jù)讀取及轉(zhuǎn)換保存

 更新時間:2026年06月05日 09:03:52   作者:ice813033181  
本文介紹了一個Python實現(xiàn)的Excel表格數(shù)據(jù)轉(zhuǎn)換工具,使用tkinter構(gòu)建GUI界面,支持讀取.xls/.xlsx文件并顯示在文本框中,同時允許用戶編輯后導(dǎo)出為.txt或.xlsx格式,有需要的可以了解下

Python代碼實現(xiàn)選擇打開.xls以及.xlsx類型的表格文件,在文本框中顯示表格數(shù)據(jù),也可以在文本框中粘貼或者編輯數(shù)據(jù),選擇導(dǎo)出.txt文本文件或者.xlsx表格文件。

(本代碼暫不支持導(dǎo)出.xls格式文件)

一、效果圖預(yù)覽

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

二、代碼運行報錯處理(pip install )

如果運行報錯,可能是沒有導(dǎo)入pandas庫的原因,可以win+r進入運行界面,輸入pip install pandas,導(dǎo)入pandas庫即可。

同理如果有其他庫缺失報錯,同樣可以(pip install 庫名)運行導(dǎo)入。

三、代碼演示

借助AI生成主體代碼后,進行優(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()

四、知識擴展

Python 讀取和轉(zhuǎn)換 Excel 數(shù)據(jù)最常用的庫是 pandas(配合 openpyxl 或 xlrd 引擎)。pandas 提供強大的數(shù)據(jù)處理能力,可以輕松完成篩選、計算、分組、合并等轉(zhuǎn)換操作。

1. 環(huán)境準備

安裝必要的庫:

pip install pandas openpyxl
  • pandas:核心數(shù)據(jù)處理庫。
  • openpyxl:讀取/寫入 .xlsx 文件引擎。

2. 讀取 Excel 數(shù)據(jù)

基本讀取

import pandas as pd

# 讀取整個 Excel 文件的第一個工作表
df = pd.read_excel('data.xlsx')
print(df.head())   # 查看前5行

指定工作表

# 按工作表名稱
df = pd.read_excel('data.xlsx', sheet_name='Sheet1')

# 按工作表索引 (0 表示第一個)
df = pd.read_excel('data.xlsx', sheet_name=0)

# 讀取多個工作表,返回字典
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ù)類型,避免自動推斷出錯
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('暫無')

列操作(新增、修改、刪除)

# 新增列(計算)
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])

# 去重(保留第一個)
df_unique = df.drop_duplicates(subset='ID')

分組聚合

# 按部門統(tǒng)計平均工資
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)

# 保存多個工作表到同一個文件
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è)有一個銷售記錄表 sales.xlsx,包含列:OrderIDProductCategorySalesQuantityDate。

任務(wù):計算每筆訂單的 Revenue,并按 Category 統(tǒng)計總銷售額,最后輸出新文件。

import pandas as pd
# 1. 讀取數(shù)據(jù)
df = pd.read_excel('sales.xlsx')
# 2. 數(shù)據(jù)清洗:檢查缺失,刪除無訂單號的記錄
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 計算總 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='明細', index=False)
    category_summary.to_excel(writer, sheet_name='分類匯總', index=False)
print("處理完成,已生成 sales_report.xlsx")

到此這篇關(guān)于Python實現(xiàn)Excel表格數(shù)據(jù)讀取及轉(zhuǎn)換保存的文章就介紹到這了,更多相關(guān)Python Excel表格數(shù)據(jù)轉(zhuǎn)換內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • 如何用Python讀取pdf中的文字與表格

    如何用Python讀取pdf中的文字與表格

    這篇文章主要介紹了如何在Python中安裝和使用PyPDF2和pdfplumber庫來處理PDF文件,包括安裝步驟、庫的使用方法以及它們在提取文本和表格方面的不同優(yōu)勢,文中通過代碼介紹的非常詳細,需要的朋友可以參考下
    2024-11-11
  • Python2與python3中 for 循環(huán)語句基礎(chǔ)與實例分析

    Python2與python3中 for 循環(huán)語句基礎(chǔ)與實例分析

    Python for循環(huán)可以遍歷任何序列的項目,如一個列表或者一個字符串,也是python中比較常用的一個函數(shù),這里通過基礎(chǔ)與實例給大家分享一下
    2017-11-11
  • 使用Python給Excel工作表設(shè)置背景色或背景圖

    使用Python給Excel工作表設(shè)置背景色或背景圖

    Excel是工作中數(shù)據(jù)處理和分析數(shù)據(jù)的重要工具,面對海量的數(shù)據(jù)和復(fù)雜的表格,如何提高工作效率、減少視覺疲勞并提升數(shù)據(jù)的可讀性是不容忽視的問題,而給工作表設(shè)置合適的背景是表格優(yōu)化的一個有效方式,本文將介紹如何用Python給Excel工作表設(shè)置背景色或背景圖
    2024-07-07
  • Python中kwargs.get()方法語法及高級用法詳解

    Python中kwargs.get()方法語法及高級用法詳解

    這篇文章主要介紹了Python中kwargs.get()方法語法及高級用法的相關(guān)資料,該方法用于安全地獲取字典中的值,并提供了默認值以避免KeyError異常,需要的朋友可以參考下
    2026-01-01
  • Python編寫繪圖系統(tǒng)之從文本文件導(dǎo)入數(shù)據(jù)并繪圖

    Python編寫繪圖系統(tǒng)之從文本文件導(dǎo)入數(shù)據(jù)并繪圖

    這篇文章主要為大家詳細介紹了Python如何編寫一個繪圖系統(tǒng),可以實現(xiàn)從文本文件導(dǎo)入數(shù)據(jù)并繪圖,文中的示例代碼講解詳細,感興趣的可以了解一下
    2023-08-08
  • python如何獲取Prometheus監(jiān)控數(shù)據(jù)

    python如何獲取Prometheus監(jiān)控數(shù)據(jù)

    這篇文章主要介紹了python如何獲取Prometheus監(jiān)控數(shù)據(jù),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-05-05
  • 如何在python中實現(xiàn)隨機選擇

    如何在python中實現(xiàn)隨機選擇

    這篇文章主要介紹了如何在python中實現(xiàn)隨機選擇,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習或者工作具有一定的參考學(xué)習價值,需要的朋友可以參考下
    2019-11-11
  • Python基于百度云文字識別API

    Python基于百度云文字識別API

    這篇文章主要介紹了Python基于百度云文字識別API,用Python實現(xiàn)最簡單的文字識別,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2018-12-12
  • Python?from?import導(dǎo)包ModuleNotFoundError?No?module?named找不到模塊問題解決

    Python?from?import導(dǎo)包ModuleNotFoundError?No?module?named

    最近在執(zhí)行python腳本時,from?import的模塊沒有被加載進來,找不到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é)

    這篇文章主要介紹了關(guān)于Numpy之repeat、tile的用法總結(jié),具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-06-06

最新評論

固阳县| 年辖:市辖区| 会昌县| 沙河市| 东台市| 横峰县| 漳浦县| 冕宁县| 南川市| 武汉市| 郎溪县| 桂阳县| 安岳县| 自治县| 宜昌市| 唐海县| 子长县| 敖汉旗| 白朗县| 射洪县| 泰来县| 砚山县| 淄博市| 称多县| 古田县| 彰化县| 盐边县| 育儿| 宜都市| 江城| 宜城市| 玉树县| 德化县| 洛南县| 临漳县| 荥阳市| 桃园市| 商都县| 寿光市| 永川市| 五家渠市|