0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Python to Export Barcode From Excel

Last updated at Posted at 2023-12-09
from PIL import Image, ImageDraw, ImageFont
from barcode import nw7
from io import BytesIO

def generate_nw7_barcode_image(cell_content, output_path):
    # NW-7形式のバーコードを生成
    code = nw7(cell_content, writer=None)
    
    # バーコードのイメージを取得
    barcode_image = code.render()

    # PillowのImageオブジェクトに変換
    pillow_image = Image.fromarray(barcode_image)

    # 画像を保存
    pillow_image.save(output_path, format='PNG')

if __name__ == "__main__":
    # セルの内容
    cell_content = "123456789"

    # 保存するPNGファイルのパス
    output_image_path = "path/to/your/output/barcode_image.png"

    # NW-7形式のバーコードを画像として生成して保存
    generate_nw7_barcode_image(cell_content, output_image_path)

other method

import zipfile
from pathlib import Path

# 画像を取り出すExcelブックのパス
xlsx_path = Path("xl_files/sample1.xlsx")

# zipfileモジュールでExcelブックを開く
xlsx_zip = zipfile.ZipFile(xlsx_path)
zipped_files = xlsx_zip.namelist()

# 画像を保存するフォルダー
img_dir = Path("xl_images")
img_dir.mkdir(exist_ok=True)

# xlsxファイルの中身を1つずつループ
for file in zipped_files:
    if file.startswith("xl/media/"):
        # 画像ファイルを開く
        img_file = xlsx_zip.open(file)
        # 画像ファイルの読み込み
        img_bytes = img_file.read()

        # 保存する画像ファイル名には、「xlsxファイル名_」を先頭に付ける
        img_path = img_dir / (xlsx_path.stem + "_" + Path(file).name)
        # 画像ファイルの保存
        with img_path.open(mode="wb") as f:
            f.write(img_bytes)
        img_file.close()

xlsx_zip.close()
Sub ReadColumnAFromCSV()
    ' CSVファイルのパスを指定してください
    Dim csvPath As String
    csvPath = "C:\path\to\your\file.csv"

    ' CSVファイルを開き、A列のみを読み込む設定で開きます
    With Workbooks.OpenText(Filename:=csvPath, _
                            Origin:=xlMSDOS, _
                            StartRow:=1, _
                            DataType:=xlDelimited, _
                            TextQualifier:=xlDoubleQuote, _
                            ConsecutiveDelimiter:=False, _
                            Tab:=False, _
                            Semicolon:=False, _
                            Comma:=True, _
                            Space:=False, _
                            Other:=False, _
                            FieldInfo:=Array(1, 1), _
                            TrailingMinusNumbers:=True)

        ' 開いたCSVファイルのデータをアクティブなワークシートのA列にコピーします
        ThisWorkbook.Sheets("Sheet1").Range("A:A").Value = _
            .Sheets(1).Range("A:A").Value

        ' 開いたCSVファイルを閉じます
        .Close SaveChanges:=False
    End With
End Sub
from openpyxl import load_workbook
from PIL import Image
from io import BytesIO

def save_picture_from_cell(excel_path, sheet_name, cell, output_path):
    wb = load_workbook(excel_path)
    sheet = wb[sheet_name]

    # 指定したセルにあるPicturesを取得
    pictures_in_cell = [pic for pic in sheet._images if pic.anchor == cell]

    for idx, picture in enumerate(pictures_in_cell):
        # 画像データをBytesIOに読み込む
        image_data = BytesIO(picture.image)
        
        # PIL Imageに変換
        img = Image.open(image_data)
        
        # 画像をPNGファイルとして保存
        img.save(f"{output_path}_pic_{idx + 1}.png", format="PNG")

    print(f"Picturesを {output_path} に保存しました。")

# Excelファイルのパス、シート名、セル、出力先を指定
excel_file_path = 'your_excel_file.xlsx'
excel_sheet_name = 'your_sheet_name'
target_cell = 'A1'  # 例: 'A1'
output_directory = 'output_path'  # 出力先ディレクトリを指定

# Picturesを指定したセルから取得し、PNGとして保存
save_picture_from_cell(excel_file_path, excel_sheet_name, target_cell, output_directory)

import zipfile
from xml.etree import ElementTree as ET

def read_shape_and_emf_info(xlsx_file_path):
    shape_info = {}

    with zipfile.ZipFile(xlsx_file_path, 'r') as zip_file:
        # 図形情報のXMLファイルを取得
        drawing_files = [name for name in zip_file.namelist() if 'drawings/drawing' in name]

        for drawing_file in drawing_files:
            with zip_file.open(drawing_file) as drawing_xml:
                tree = ET.parse(drawing_xml)
                root = tree.getroot()

                # 各図形の名前とEMFファイルへのパスを取得
                for shape in root.findall('.//xdr:sp', namespaces={'xdr': 'http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing'}):
                    name_element = shape.find('.//xdr:nvSpPr/xdr:cNvPr', namespaces={'xdr': 'http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing'})
                    if name_element is not None:
                        shape_name = name_element.get('name', '')
                        emf_path_element = shape.find('.//a:blip', namespaces={'a': 'http://schemas.openxmlformats.org/drawingml/2006/main'})
                        
                        if emf_path_element is not None:
                            emf_path = emf_path_element.get('{http://schemas.openxmlformats.org/officeDocument/2006/relationships}embed', '')
                            shape_info[shape_name] = emf_path

    return shape_info

# Excelファイルのパスを指定
xlsx_file_path = 'path/to/your/excel/file.xlsx'

# 図形情報から図形の名前とEMFファイルへのパスを取得
shape_info = read_shape_and_emf_info(xlsx_file_path)

# 結果を表示
for shape_name, emf_path in shape_info.items():
    print(f"Shape Name: {shape_name}, EMF Path: {emf_path}")
for sp in root.findall('.//xdr:sp', namespaces={'xdr': 'http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing'}):
    # xdr:sp 要素が見つかった場合
    blip_element = sp.find('.//a:blip', namespaces={'a': 'http://schemas.openxmlformats.org/drawingml/2006/main'})
    if blip_element is not None:
        # a:blip 要素が見つかった場合
        emf_path = blip_element.get('{http://schemas.openxmlformats.org/officeDocument/2006/relationships}embed', '')
        print("EMF Path:", emf_path)
    else:
        print("a:blip not found under xdr:sp")
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?