0
3

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 3 years have passed since last update.

【Python】編集中のExcelの指定した範囲をgoogle翻訳する

Last updated at Posted at 2021-05-18

###はじめに
編集中のExcelのセルを手軽にGoogle翻訳するためのコードです.ファイルを閉じたりファイル名を指定して実行したりするのが面倒な方向けです.

###開発環境
windows10
Python-3.9.4
使用ライブラリ pywin32, datetime, googletrans

###コード

import win32com.client
import datetime
from googletrans import Translator
translator =  Translator()

#開いているExcelbookを取得.複数開いている場合最初に開いていたものが指定されるはずですが、bookは1つしか開いていない前提です.
xl = win32com.client.GetObject(Class="Excel.Application")

#ActiveSheetを取得
ws = xl.ActiveSheet

#Excelを起動したまま
xl.Visible = True

#翻訳したい列
column = "A"
#翻訳結果を書き込む列
column_result = "B"
#翻訳したい行範囲を書き込む
row_s = 3
row_e = 200

for row in range(row_s, row_e+1):
  # cell        : 翻訳対象のセル
  # cell_result : 翻訳結果を書き込むセル
  row = str(row)
  cell = ws.Range(column+row)
  cell_result = ws.Range(column_result+row)

  # 空欄などには翻訳を実行しない
  if cell.value is None:
    pass
  elif isinstance(cell.value,int):
    pass
  elif isinstance(cell.value,datetime.time):
    cell.number_format = "h:mm"
    pass
  elif isinstance(cell.value,datetime.datetime):
    cell.number_format = "yyyy/m/d"
    pass
  else:
    cell_result.value = translator.translate(str(cell.value),src="en", dest="ja").text

0
3
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
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?