码迷,mamicode.com
首页 > 其他好文 > 详细

XLSX to CSVs (通用)

时间:2015-05-08 20:03:54      阅读:275      评论:0      收藏:0      [点我收藏+]

标签:

# Copyright (c) 2012, Bryan O‘Connell
# License: http://bryanoconnell.blogspot.com/p/licenses.html
# Purpose: Extract all of the worksheets from an Excel file into separate files.
[CmdletBinding()]
Param (
    [Parameter(Mandatory=$true,Position=0)]
    [string]$filepath,
    [Parameter(Mandatory=$true,Position=1)]
    [ValidateSet("csv","txt","xls","html")]
    [string]$output_type
)
#-----------------------------------------------------------------------------#
# Figures out and returns the ‘XlFileFormat Enumeration‘ ID for the specified format.
# http://msdn.microsoft.com/en-us/library/office/bb241279%28v=office.12%29.aspx
# NOTE: The code being used for ‘xls‘ is actually a ‘text‘ type, but it seemed
# to work the best for splitting the worksheets into separate Excel files.
function GetOutputFileFormatID
{
Param([string]$fomat_name)
    $Result = 0
    switch($fomat_name)
    {
        "csv" {$Result = 6}
        "txt" {$Result = 20}
        "xls" {$Result = 21}
        "html" {$Result = 44}
        default {$Result = 51}
    }
   
    return $Result
}
#-----------------------------------------------------------------------------#
$Excel = New-Object -ComObject "Excel.Application"
$Excel.Visible = $false #Runs Excel in the background.
$Excel.DisplayAlerts = $false #Supress alert messages.
$Workbook = $Excel.Workbooks.open($filepath)
#Loop through the Workbook and extract each Worksheet
# in the specified file type.
if ($Workbook.Worksheets.Count -gt 0) {
    write-Output "Now processing: $WorkbookName"
   
    $FileFormat = GetOutputFileFormatID($output_type)
    #Strip off the Excel extension.
    $WorkbookName = $filepath -replace ".xlsx", "" #Post 2007 extension
    $WorkbookName = $WorkbookName -replace ".xls", "" #Pre 2007 extension
    #$Worksheet = $Workbook.Worksheets.item(1)
    foreach($Worksheet in $Workbook.Worksheets) {
        $ExtractedFileName = $WorkbookName + "~~" + $Worksheet.Name + "." + $output_type
        $Worksheet.SaveAs($ExtractedFileName, $FileFormat)
        write-Output "Created file: $ExtractedFileName"
    }
}
#Clean up & close the main Excel objects.
$Workbook.Close()
$Excel.Quit()

 

http://bryanoconnell.blogspot.jp/2012/09/extract-worksheets-from-excel.html

XLSX to CSVs (通用)

标签:

原文地址:http://www.cnblogs.com/IvanChen/p/4488586.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!