I tried to create a Python script to get the value of a cell in Microsoft Excel

1. Install MSYS2

Download the latest version of MSYS2 from https://www.msys2.org/ and install it on Windows 10. msys2.png

2. Install Python and openpyxl

Start "SYS2 64bit"-"MSYS2 MinGW 64-bit" from the start menu and execute the following.

# pacman -Qe
# yes | pacman -S mingw-w64-x86_64-python mingw-w64-x86_64-python-openpyxl
# pacman -Qe

3. Script creation

excellsp.py


#!/usr/bin/env python3

import sys
import getopt
import openpyxl

def usage():
    print('usage: ' + sys.argv[0] + \
        ' [ -h -q quotation -s separator ] workbook worksheet [celladdr...]', \
        file=sys.stderr)

try:
    opts,argv = getopt.getopt(sys.argv[1:], "hq:s:")
except getopt.GetoptError as err:
    print(err)
    usage()
    sys.exit(1)

separator = '\n'
quotation = ''

for opt,optarg in opts:
    if opt == "-h":
        usage()
        print("Pass2")
        sys.exit()
    elif opt == '-q':
        quotation = optarg
    elif opt == '-s':
        separator = optarg
    else:
        print("Pass1")
        usage()
        sys.exit(1)

if len(argv) < 2:
    usage()
    sys.exit(1)

wb = openpyxl.load_workbook(argv[0])
ws = wb[argv[1]]
del argv[:2]

separator = separator.replace('\\t', '\t').replace('\\n', '\n')
output = ''

for arg in argv:
    value = str(ws[arg].value);
    if quotation != '':
        value = quotation + value.replace(quotation, quotation + quotation) + \
            quotation;
    if output != '':
        output += separator
    output += value

print(output)

4. Create a test book

Create a workbook "Book1.xlsx" with the following sheet "Sheet1" in Microsoft Excel.

A B C D E
1 a1 b1 c1 d1
2 a2 b2 c2 d2
3 a3 b3 c3 d"3
4 a4 b4 c4 d4

5. Run the script

# chmod a+x excellsp.py
# ./excellsp.py -h
usage: ./excellsp.py [ -h -q quotation -s separator ] workbook worksheet [celladdr...]
# ./excellsp.py Book1.xlsx Sheet1 A1 C2 D3 E4
a1
c2
d"3
e4
# ./excellsp.py -s '\t' Book1.xlsx Sheet1 A1 C2 D3 E4
a1	c2	d"3	e4
# ./excellsp.py -q '"' -s '\t' Book1.xlsx Sheet1 A1 C2 D3 E4
"a1"	"c2"	"d""3"	"e4"


Recommended Posts

I tried to create a Python script to get the value of a cell in Microsoft Excel
I tried to display the altitude value of DTM in a graph
[Azure] I tried to create a Linux virtual machine in Azure of Microsoft Learn
I tried "How to get a method decorated in Python"
How to get the last (last) value in a list in Python
[Python & SQLite] I tried to analyze the expected value of a race with horses in the 1x win range ①
I tried to create a list of prime numbers with python
Create a function to get the contents of the database in Go
Get the value of a specific key up to the specified index in the dictionary list in Python
[OCI] Python script to get the IP address of a compute instance in Cloud Shell
I wrote a doctest in "I tried to simulate the probability of a bingo game with Python"
Get the caller of a function in Python
I want to create a window in Python
I tried to get the authentication code of Qiita API with Python.
I want to color a part of an Excel string in Python
I tried to get the movie information of TMDb API with Python
I made a program to check the size of a file in Python
I tried to implement a card game of playing cards in Python
I tried to graph the packages installed in Python
How to get the number of digits in Python
I tried to create a class that can easily serialize Json in Python
To output a value even in the middle of a cell with Jupyter Notebook
I tried to implement a pseudo pachislot in Python
I tried to open the latest data of the Excel file managed by date in the folder with Python
Python script to get a list of input examples for the AtCoder contest
[Python] I tried to get the type name as a string from the type function
I made a script to record the active window using win32gui of Python
[Python] I tried to get Json of squid ring 2
How to get a list of files in the same directory with python
I tried to create a model with the sample of Amazon SageMaker Autopilot
I tried to summarize the string operations of Python
I created a script to check if English is entered in the specified position of the JSON file in Python.
I wanted to know the number of lines in multiple files, so I tried to get it with a command
Get the value of a specific key in a list from the dictionary type in the list with Python
[Python] I tried to automatically create a daily report of YWT with Outlook mail
I tried to find the entropy of the image with python
I tried to get the location information of Odakyu Bus
I tried the accuracy of three Stirling's approximations in python
I tried to create API list.csv in Python from swagger.yaml
I tried to implement a one-dimensional cellular automaton in Python
Get the number of specific elements in a python list
[Python] I tried to visualize the follow relationship of Twitter
How to get a list of built-in exceptions in python
I wrote a script to get a popular site in Japan
I tried to implement the mail sending function in Python
I tried to make a stopwatch using tkinter in python
I tried changing the python script from 2.7.11 to 3.6.0 on windows10
I tried to implement blackjack of card game in Python
Get the script path in Python
(Python: OpenCV) I tried to output a value indicating the distance between regions while binarizing the video in real time.
I tried to create a RESTful API by connecting the explosive Python framework FastAPI to MySQL.
I made a class to get the analysis result by MeCab in ndarray with python
I also tried to imitate the function monad and State monad with a generator in Python
I tried to get a database of horse racing using Pandas
How to determine the existence of a selenium element in Python
I tried to get the index of the list using the enumerate function
Try to get a list of breaking news threads in Python.
I tried to make a regular expression of "amount" using Python
How to check the memory size of a variable in Python
Create a shell script to run the python file multiple times
I tried to make a regular expression of "time" using Python