ちょいめも

物理/Python/Cの雑記帳

xlsxを開いてcsvに値を保存

import sys
import os
import re
import glob
import csv
import win32com.client

class func():
		
	def __init__(self, load_path=''):
		
		self.dir, self.file = os.path.split(load_path)
		self.load_path = load_path

	def read_xlsx(self):

		xlApp = win32com.client.Dispatch("Excel.Application")
		xlApp.DisplayAlerts = False
		
		wb = xlApp.Workbooks.Open(self.load_path)
		sheet = wb.Worksheets("Sheet1")
		
		a = sheet.Range("A1").Value
		b = sheet.Range("B1").Value

		wb.Close()
		xlApp.Quit()
		wb = None
		xlApp = None

		if not os.path.isfile('summary.csv'):
			f = open('summary.csv', 'w')
			f.close()
			
		f = open('summary.csv', 'a', newline='')
		csvWriter = csv.writer(f)
		csvWriter.writerow([a,b])
		f.close()
		
if __name__ == '__main__':
	
	argvs = sys.argv 
	argc = len(argvs) #引数の個数
	
	if argc != 2:
		sys.exit()
	
	if re.search('.xlsx',argvs[1]):
		try:
			sheet = func(argvs[1])
			sheet.read_xlsx()
		except:
			print('Error : Input file is not supported.')
			sys.exit()
	else:
		try:
			xlsx_list = glob.glob('%s/*.xlsx' % argvs[1])
			
			if len(xlsx_list) != 0:
				for i in xlsx_list:
					sheet = func(i)
					sheet.read_xlsx()
			else:
				print('Error : Input file/folder is not supported.')
				sys.exit()
			
		except:
			print('Error : Input file is not supported.')
			sys.exit()