2011-02-15 5 views
0

원래 Excel에서 XML 파일을 열려고했습니다. 그러나 나이가 들수록 XML을 탭으로 구분 된 텍스트 파일로 구문 분석했습니다. 인터넷에서 올바른 구문을 발견했다고 생각했습니다. Excel 매크로로 기록한 값을 사용하여 아래 코드를 시도했습니다. 18 열 탭으로 구분 된 파일이 있습니다. "워크 시트"메서드를 호출 할 때 아래 코드의 마지막 줄에 오류가 발생합니다.Perl 및 OLE를 사용하여 Excel에서 탭으로 구분 된 텍스트 파일을 여는 방법은 무엇입니까?

오류 메시지 : ./PostProcessingDev.pl 라인에서 패키지 또는 객체를 참조하지 않고 방법 "워크 시트"를 호출 할 수 없습니다 (70)

use Win32::OLE; 
use Win32::OLE::Const 'Microsoft Excel'; 
Win32::OLE->Option(Warn => 3); 

use strict; 

my $Excel; 
my $Sheet; 
my $Workbook; 


$Excel = CreateObject OLE "Excel.Application"; 

$Workbook = $Excel->Workbooks->OpenText({Filename =>"$inSelf->{'TXT'}", 
    Origin => xlMSDOS, 
    StartRow => 1, 
    DataType => xlDelimited, 
    TextQualifier => xlDoubleQuote, 
    ConsecutiveDelimiter => "False", 
    Tab => "True", 
    Semicolon => "False", 
    Comma => "False", 
    Space => "False", 
    Other => "False", 
    FieldInfo => [[1, xlTextFormat], 
    [2, xlTextFormat], 
    [3, xlTextFormat], 
    [4, xlTextFormat], 
    [5, xlTextFormat], 
    [6, xlTextFormat], 
    [7, xlTextFormat], 
    [8, xlTextFormat], 
    [9, xlTextFormat], 
    [10, xlTextFormat], 
    [11, xlTextFormat], 
    [12, xlTextFormat], 
    [13, xlTextFormat], 
    [14, xlTextFormat], 
    [15, xlTextFormat], 
    [16, xlTextFormat], 
    [17, xlTextFormat], 
    [18, xlTextFormat]], 
    TrailingMinusNumbers => "True"}); 

$Sheet = $Workbook->Worksheets(1); 

답변

2

당신은 정말 사용 TSV를 구문 분석해야합니까 뛰어나다? 파일에 공상 아무것도 존재하지 않는 경우, 당신은 잘 같은 것을 사용할 수 있습니다 : 엑셀은 내가 볼 수없는 이유가 필요한 경우

my $file = 'some tsv file'; 
{ 
    open my $in,"<",$file or die "$file: $!"; 
    while(<$in>) { 
     chomp; 
     my @cols = split /\t/; 
     # do something with columns in @cols array 
    } 
} 

, 문제는 OpenText 방법은 참/거짓 반환하고 있지 Workbook 객체입니다. 작동 방식 :

use strict; 

use Win32::OLE; 
use Win32::OLE::Const 'Microsoft Excel'; 
use Data::Dump;  # for dd 

Win32::OLE->Option(Warn => 3); 

my $Excel = Win32::OLE->new("Excel.Application"); 
$Excel->Workbooks->OpenText({ 
    Filename    => 'enter the full path to file', 
    Origin    => xlMSDOS, 
    StartRow    => 1, 
    DataType    => xlDelimited, 
    TextQualifier  => xlDoubleQuote, 
    Tab     => "True", 
    TrailingMinusNumbers => "True" 
}); 

my $Sheet = $Excel->ActiveWorkbook->Worksheets(1); 
my $Data = $Sheet->UsedRange()->{Value}; 

dd $Data; # arrayref (rows) of arrayrefs (columns) 
+0

xSV 파일을 스플릿/정규식으로 구문 분석해서는 안됩니다. CSV와 동일하게 적절한 모듈을 사용하십시오 (텍스트 : CSV_CS) – DVK

+0

빠른 답변 감사드립니다. Excel을 구문 분석기로 사용하지 않습니다. 구문 분석 부분에서는 필요한 mudules를 사용하거나 설치할 수 없으므로 직접 작성했습니다. 나는 진주 배열 안의 모든 것을하고있다. TSV 및 Excel 파일이 출력입니다. TSV를 여는 것과 비교하여 필자의 Excel 셀 셀 (Cell by Cell)은 TSV를 열고 Excel로 저장하기를 원할 때보 다 느리다 (10 분의 1 줄). 4 줄의 텍스트 파일에서 코드를 실행하면 OpenText 메서드 안에 갇히게됩니다. 어떻게되는지 어떻게 알 수 있습니까? OLE 메서드를 디버깅 할 수 있습니까? – user617474

+0

나는 당신이 원하는 것을 제대로 이해하지 못했습니다. 확장자가 .CSV 인 CSV를 작성하면 Excel이 연결되어 직접 열 수 있습니다. 'OLE' 디버깅 당, 약간 까다 롭지 만, 초기화 후에'$ Excel -> {Visible} = 1;'을 넣을 수 있으며 Excel에서 무엇이 진행되고 있는지 볼 수 있습니다. – bvr

0

Text::CSV을 사용해보세요. 사용자 정의 구분 기호를 지원합니다. 모듈 설명을 참조하십시오.

0

답장을 보내 주셔서 감사합니다. 이 문제가 해결되었습니다. OpenText 메서드로하고 싶었던 것은 TSV 파일을 Excel로 변환하는 것이었기 때문에 결과 형식이 필요했습니다. 전체 코드를 제공하기 전에 웹에서 솔루션을 찾을 수 없었기 때문에 :

use Win32::OLE; 
use Win32::OLE::Const 'Microsoft Excel'; 
use strict; 

Win32::OLE->Option(Warn => 3); 

my $FileName = "Complete Path of TSV File"; 

my $Excel = Win32::OLE->new("Excel.Application"); 

# Open Tab separated Text file in Excel, all 18 columns are "Text" formated 
$Excel->Workbooks->OpenText({ 
    Filename  => $FileName, 
    Origin  => xlMSDOS, 
    StartRow  => 1, 
    DataType  => xlDelimited, 
    TextQualifier => xlDoubleQuote, 
    Tab   => "True", 
    FieldInfo  => [[1, xlTextFormat], 
    [2, xlTextFormat], 
    [3, xlTextFormat], 
    [4, xlTextFormat], 
    [5, xlTextFormat], 
    [6, xlTextFormat], 
    [7, xlTextFormat], 
    [8, xlTextFormat], 
    [9, xlTextFormat], 
    [10, xlTextFormat], 
    [11, xlTextFormat], 
    [12, xlTextFormat], 
    [13, xlTextFormat], 
    [14, xlTextFormat], 
    [15, xlTextFormat], 
    [16, xlTextFormat], 
    [17, xlTextFormat], 
    [18, xlTextFormat]], 
    TrailingMinusNumbers => "True" 
}); 

my $Sheet = $Excel->ActiveWorkbook->Worksheets(1); 
$Sheet->Activate; 

my $Workbook = $Excel->ActiveWorkbook; 

# Replace the "*.txt" file extension by "*.xls" for Excel 
$FileName =~ s/txt$/xls/; 

# Turn off the "This file already exists" message. 
$Excel->{DisplayAlerts} = 0; 
# Save file as Excel 2000-2003 Workbook (command for Excel 2007) 
$Workbook->SaveAs({Filename => $FileName, FileFormat => xlExcel8}); 
$Excel->Quit; 
관련 문제