Last active
January 13, 2017 09:03
-
-
Save ap0llo/800423c9a81fc76ce795358069556861 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Powershell script to export tables from excel to LaTeX markup | |
function ConvertTo-Latex($inputFile, $sheetName, $startX, $startY, $endX, $endY, $outputFile) | |
{ | |
function Get-LatexTableOptions($columnCount) | |
{ | |
$options = "|" | |
for($i = 0; $i -lt $columnCount; $i = $i + 1) | |
{ | |
$options = $options + " c |" | |
} | |
return $options | |
} | |
# Load Powerpoint Interop Assembly | |
[Reflection.Assembly]::LoadWithPartialname("Microsoft.Office.Interop.Excel") > $null | |
[Reflection.Assembly]::LoadWithPartialname("Office") > $null | |
$msoFalse = [Microsoft.Office.Core.MsoTristate]::msoFalse | |
$msoTrue = [Microsoft.Office.Core.MsoTristate]::msoTrue | |
# start Excel | |
$application = New-Object "Microsoft.Office.Interop.Excel.ApplicationClass" | |
# Make sure inputFile is an absolte path | |
$inputFile = Resolve-Path $inputFile | |
$outputFile = [System.IO.Path]::GetFullPath($outputFile) | |
$workbook = $application.Workbooks.Open($inputFile) | |
$sheet = $workbook.Worksheets.Item($sheetName) | |
$options = Get-LatexTableOptions ($endX - $startX + 1) | |
Out-File $outputFile -InputObject "\begin{tabular}{$($options)} \firsthline" -Encoding ASCII | |
$y = $startY | |
while($y -le $endY) | |
{ | |
$line = "`t" | |
$x = $startX | |
while($x -le $endX) | |
{ | |
$value = $sheet.Cells.Item($y, $x).Text | |
if($x -eq $startX) | |
{ | |
$line = $line + $value | |
} | |
else | |
{ | |
$line = $line + " & " + $value | |
} | |
$x++ | |
} | |
$line = $line + " \\\hline" | |
Out-File $outputFile -InputObject $line -Append -Encoding ASCII | |
$y++ | |
} | |
Out-File $outputFile -InputObject "\end{tabular}" -Append -Encoding ASCII | |
$sheet = $null | |
$workbook.Close($msoFalse) | |
$workbook = $null | |
if($application.Windows.Count -eq 0) | |
{ | |
$application.Quit() | |
} | |
$application = $null | |
# Make sure references to COM objects are released, otherwise powerpoint might not close | |
# (calling the methods twice is intentional, see https://msdn.microsoft.com/en-us/library/aa679807(office.11).aspx#officeinteroperabilitych2_part2_gc) | |
[System.GC]::Collect(); | |
[System.GC]::WaitForPendingFinalizers(); | |
[System.GC]::Collect(); | |
[System.GC]::WaitForPendingFinalizers(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment