Cynthia
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Note Insights Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    --- title: 【Python】讀取與寫入 xlsx 檔案 date: 2020-12-21 22:08 is_modified: false disqus: cynthiahackmd categories: - "程式設計 › 程式語言與架構" tags: - "程式設計 › 程式語言與架構" - "Python" --- {%hackmd @CynthiaChuang/Github-Page-Theme %} <br> 那天,我媽的同事傳了份檢驗結果文件給她,但格式超級奇怪,既不是人工閱讀的文件格式、也不是資料系統的處理格式。我媽想把它轉成資料系統格式,可偏偏 Excel 的轉置、公式什麼的都沒辦法處理、公式什麼的都沒辦法處理,只能人工處理。粗估下來,一份小資料大概 2 小時跑不掉。 我看了一下資料內容,是可以抓到一些規律的,因此打算寫程式幫她轉了,如果一切順利 15 分鐘就可以解決了。漏氣的是,第一關讀檔就卡住,我之前好像還沒有讀過 Excel 檔的文件。 <!--more--> ## 一般讀檔案 原本想說它跟 CSV 檔案類似,可以用一般讀檔的方式讀進來,結果一開始就吃鱉了。 ```python= with open("原料年檢資料.xlsx", "r", encoding="utf-8") as fr: for line in fr : print(line) ``` 立刻給了我個編碼問題,看來不能偷吃步了,只好來研究怎麼讀 Excle 檔了。 ```bash= UnicodeDecodeError: 'utf-8' codec can't decode byte 0x90 in position 16: invalid start byte ``` ## Pandas 讀檔 拜了一下大神,發現有 openpyxl、 xlrd、 Pandas 幾種函式庫有支援 xlsx 的讀寫。最決定用 Pandas,因為我平常資料操作都是用它,就不用另外裝函式庫了。 - [Python 讀寫 Excel 文件--使用 xlrd 模塊讀取,xlwt 模塊寫入](https://www.itread01.com/content/1507641632.html) - [Python 使用 openpyxl 讀寫 Excel 檔案的方法](https://codertw.com/%E7%A8%8B%E5%BC%8F%E8%AA%9E%E8%A8%80/365164/) ```python= import pandas as pd df=pd.read_excel("原料年檢資料.xlsx") # 印出前四筆資料 df.head(4) # 轉成 numpy.ndarray 格式 nmp=df.values ``` 讀進來之後就變 Pandas 格式了,可以接續一般的操作了。不過我在執行程式碼時遇到下面的錯誤訊息: ```bash= Pandas pd.read_excel giving ImportError: Install xlrd >= 0.9.0 for Excel support ``` 看起來是安裝 xlrd 0.9.0 以上的版本就可以了,結果還是得裝套新的函式庫: ```bash= $pip install xlrd ``` ## Pandas 寫檔 至於寫檔的部分我其實偷懶,寫了 CSV 出去,反正給 CSV 我媽他們系統也可以接受。 不過為了寫網誌,還是[稍微看了一下如何寫檔](https://shihs.github.io/blog/python/2019/01/02/Python-%E8%AE%80%E5%8F%96%E8%88%87%E5%AF%AB%E5%85%A5xlsx%E6%AA%94%E6%A1%88/),算是留個記錄方便日後找查,絕對不是我不想再多裝個函式庫 XDDD ```python= # 因為我要寫中文檔案 engine 要換成 openpyxl writer = pd.ExcelWriter('pandas_simple.xlsx', engine='openpyxl') # df 指要寫出的內容 df.to_excel(writer, sheet_name='Sheet1') writer.save() ``` 看這段程式碼沒意外還是得安裝 openpyxl: ```bash= $pip install openpyxl ``` ## 參考資料 1. M.C. Shih (2019-01-02)。[[Python]讀取與寫入xlsx檔案](https://hackmd.io/qmlrnWi6SjqNiS7LendEaQ?edit) 。檢自 M.C. Shih (2020-07-31)。 ## 更新紀錄 :::spoiler 最後更新日期:2020-12-21 - 2020-12-21 發布 - 2020-09-12 完稿 - 2020-09-11 起稿 ::: <br><br> > **本文作者**: 辛西亞.Cynthia > **本文連結**: [辛西亞的技能樹](https://cynthiachuang.github.io/How-to-Read-a-Xlsx-File-Using-the-Pandas-Library-in-Python/) / [hackmd 版本](https://hackmd.io/@CynthiaChuang/How-to-Read-a-Xlsx-File-Using-the-Pandas-Library-in-Python) > **版權聲明**: 部落格中所有文章,均採用 [姓名標示-非商業性-相同方式分享 4.0 國際](https://creativecommons.org/licenses/by-nc-sa/4.0/deed.en) (CC BY-NC-SA 4.0) 許可協議。轉載請標明作者、連結與出處!

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully