如何使用 Python 將資料寫入 Excel 電子表格
許多開發人員都遇到需要將資料從程式匯出到 Excel 電子表格的情況。本指南將探索 Python 中用於完成此任務的不同方法和套件。
選擇方法
選擇方法時,請考慮項目的特定要求。需要記住的因素包括目標電腦上 Office 的可用性以及資料的長度和結構。
使用 Openpyxl
Openpyxl 是一個流行的 Python 軟體包,用於讀取和寫入 Excel 電子表格。它提供了對單元格格式和樣式的靈活性和深入控制。但是,請記住,Openpyxl 要求在目標系統上安裝 Office,這可能並不總是可行。
利用 Pandas
對於未安裝 Office 或未安裝 Office 的情況資料很複雜,Pandas 成為一個很好的選擇。 Pandas 允許您以通用資料結構操作和表示資料。透過將資料轉換為 DataFrame 並利用 to_excel 方法,您可以輕鬆地將其儲存到 Excel 檔案中。
範例用例
考慮一個場景,其中您有兩個值清單和三個值清單字串變數。您需要建立一個具有特定版面的Excel 文件,如下圖所示:
使用Openpyxl,您可以如下建立此版面:
import openpyxl data = { "Display": [1, 2, 3], "Dominance": [2.34, 4.346, 4.234], "Test": [2.3, 3.2, 1.7] } workbook = openpyxl.Workbook() sheet = workbook.active # Set column widths sheet.column_dimensions["A"].width = 10 sheet.column_dimensions["B"].width = 15 # Insert headings sheet["A1"] = "Category" sheet["B1"] = "Values" # Iterate over keys and values for key, values in data.items(): sheet[f"A{sheet.max_row + 1}"] = key for i, value in enumerate(values, 2): sheet[f"B{sheet.max_row + i}"] = value workbook.save("output.xlsx")
或者,使用Pandas:
import pandas as pd data = { "display": [1, 2, 3], "dominance": [2.34, 4.346, 4.234], "test": [2.3, 3.2, 1.7] } df = pd.DataFrame(data) df.to_excel("output.xlsx", index=False)
格式化單元格
要將特定單元格格式化為科學或精確數字,您可以利用Pandas 中的樣式方法:
df['dominance'] = df['dominance'].apply(lambda x: "%.10f" % x) df.to_excel("output.xlsx", index=False)
這將在將值格式化為科學的同時保留值的完整精度符號。
以上是如何使用 Python 將資料寫入 Excel 電子表格:Openpyxl 與 Pandas?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

pythonisehybridmodeLofCompilation和interpretation:1)thepythoninterpretercompilesourcecececodeintoplatform- interpententbybytecode.2)thepythonvirtualmachine(pvm)thenexecutecutestestestestestesthisbytecode,ballancingEaseofuseEfuseWithPerformance。

pythonisbothinterpretedAndCompiled.1)它的compiledTobyTecodeForportabilityAcrosplatforms.2)bytecodeisthenInterpreted,允許fordingfordforderynamictynamictymictymictymictyandrapiddefupment,儘管Ititmaybeslowerthananeflowerthanancompiledcompiledlanguages。

在您的知識之際,而foroopsareideal insinAdvance中,而WhileLoopSareBetterForsituations則youneedtoloopuntilaconditionismet

ForboopSareSusedwhenthentheneMberofiterationsiskNownInAdvance,而WhileLoopSareSareDestrationsDepportonAcondition.1)ForloopSareIdealForiteratingOverSequencesLikelistSorarrays.2)whileLeleLooleSuitableApeableableableableableableforscenarioscenarioswhereTheLeTheLeTheLeTeLoopContinusunuesuntilaspecificiccificcificCondond

pythonisnotpuroly interpred; itosisehybridablectofbytecodecompilationandruntimeinterpretation.1)PythonCompiLessourceceCeceDintobyTecode,whitsthenexecececected bytybytybythepythepythepythonvirtirtualmachine(pvm).2)

concatenateListSinpythonWithTheSamelements,使用:1)operatoTotakeEpduplicates,2)asettoremavelemavphicates,or3)listcompreanspherensionforcontroloverduplicates,每個methodhasdhasdifferentperferentperferentperforentperforentperforentperfornceandordorimplications。

pythonisanterpretedlanguage,offeringosofuseandflexibilitybutfacingperformancelanceLimitationsInCricapplications.1)drightingedlanguageslikeLikeLikeLikeLikeLikeLikeLikeThonexecuteline-by-line,允許ImmediaMediaMediaMediaMediaMediateFeedBackAndBackAndRapidPrototypiD.2)compiledLanguagesLanguagesLagagesLikagesLikec/c thresst

Useforloopswhenthenumberofiterationsisknowninadvance,andwhileloopswheniterationsdependonacondition.1)Forloopsareidealforsequenceslikelistsorranges.2)Whileloopssuitscenarioswheretheloopcontinuesuntilaspecificconditionismet,usefulforuserinputsoralgorit


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

Video Face Swap
使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

MantisBT
Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

SublimeText3 英文版
推薦:為Win版本,支援程式碼提示!

MinGW - Minimalist GNU for Windows
這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

DVWA
Damn Vulnerable Web App (DVWA) 是一個PHP/MySQL的Web應用程序,非常容易受到攻擊。它的主要目標是成為安全專業人員在合法環境中測試自己的技能和工具的輔助工具,幫助Web開發人員更好地理解保護網路應用程式的過程,並幫助教師/學生在課堂環境中教授/學習Web應用程式安全性。 DVWA的目標是透過簡單直接的介面練習一些最常見的Web漏洞,難度各不相同。請注意,該軟體中

EditPlus 中文破解版
體積小,語法高亮,不支援程式碼提示功能