Note that there are some explanatory texts on larger screens.

plurals
  1. POFilling an excel file with python is messing up my dates
    primarykey
    data
    text
    <p>Here is the process, I have an xlsm file called template, inside a worksheet called data. Then I have 5 Csv files, I must put the content of all csv file inside the data worksheet.</p> <p>No problems to do that, except if a date is "07/09/12" it will become "09/07/12" in excel.</p> <p>So I have a list called data, here is a print of one of it's line</p> <pre><code>['07/09/12', 'LARO', 'MEDITERRAN', '245', 'UZES', '11', '0', '0', '0', '0', '11', '0'] </code></pre> <p>I'm putting the in the excel file with this piece of code :</p> <p>First I open the file (xl is because I use "with self as xl")</p> <pre><code>def open(self): self.xl.Visible = 1 self.xl.ScreenUpdating = False self.worksheet = self.xl.Workbooks.Open(self.getOutputFile()) </code></pre> <p>Then I erase the data worksheet</p> <pre><code>def cleanData(self): sheet = self.xl.Sheets(self.sheetName) def findNumberOfLines(start_line): nb = 0 while sheet.Cells(start_line + nb, self.startColumn).Value is not None: nb += 1 return nb </code></pre> <p>Then I fill the data</p> <pre><code>def fillData(self): sheet = self.xl.Sheets(self.sheetName) noRow = self.startLine for row in self.data: noCol = self.startColumn for i, value in enumerate(row): sheet.Cells(noRow, noCol).Value = value noCol+=1 noRow+=1 </code></pre> <p>And I save</p> <pre><code>def save(self): self.worksheet.Save() </code></pre> <p>And everythong is good except the day and month are inverted inside excel (it's not displaying US format, it's displaying EUR format with month and day inverted (3 october becomes 9 march, tested using "long date" format)</p> <p>Weird thing : the excel cell containing dates is set at "standard" but once it has been filed by my python script it's set at "date"</p> <p><strong>WORKAROUND</strong> when filling the sheet I'm intercepting every date and converting them to datetime, excel seems to like that</p> <pre><code>def fillData(self): sheet = self.xl.Sheets(self.sheetName) noRow = self.startLine pattern = re.compile('^\d+/\d+/\d+$') for row in self.data: noCol = self.startColumn for i, value in enumerate(row): if (pattern.match(str(value))): date = value.rsplit('/') sheet.Cells(noRow, noCol).Value = datetime(int(date[2]), int(date[1]), int(date[0])) else: sheet.Cells(noRow, noCol).Value = value noCol+=1 noRow+=1 </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload