Board logo

标题: [文本处理] 批处理怎样将多个文本文件指定位置的内容放入excel? [打印本页]

作者: alan359    时间: 2019-8-28 23:05     标题: 批处理怎样将多个文本文件指定位置的内容放入excel?

仪器测量的一系列数据,只能保存成文本文档,比如现在有一系列文档data.0 , data0.0 , data1.0 , data2.0 ,……,(.0扩展名是仪器自动设置,其实就是文本文档),每个文本里面每一行有两个数据,其中第一列内容每个文件均相同,第二列为每次测量数据,第一列和第二列之间逗号隔开。现在需要将这些文档数据放到excel里面处理,所以希望通过批处理实现:1. 新建.csv文件,csv文件名为当前文件夹名称,2. 将data.0 的第一列数据放到excel第一列,将data.0 的第二列数据放到excel第二列,将data0.0的第二列数据放到excel的第三列,将data1.0的第二列数据放到excel第四列,……以此类推直到将所有文档内容导入excel中。恳请大神们帮帮忙!
作者: alan359    时间: 2019-8-28 23:09

本帖最后由 alan359 于 2019-8-28 23:12 编辑

如data.0为  100,0   data0.0为  100,4        data1.0为  100,8    希望导入excel后为  100,0,4,8
                200,1                   200,5                        200,9                               200,1,5,9
                300,2                   300,6                        300,10                             300,2,6,10
                400,3                   400,7                        400,11                             400,3,7,11
作者: zaqmlp    时间: 2019-8-29 00:07

  1. <# :
  2. @echo off
  3. set info=互助互利,支付宝扫码头像,感谢赞助
  4. rem 有问题,可加QQ956535081及时沟通
  5. title %info%
  6. set "rootpath=%~dp0"
  7. if "%rootpath:~-1%" equ "\" (set "rootpath=%rootpath:~,-1%")
  8. cd /d "%rootpath%"
  9. powershell -NoProfile -ExecutionPolicy bypass "Invoke-Command -ScriptBlock ([ScriptBlock]::Create([IO.File]::ReadAllText('%~f0',[Text.Encoding]::Default))) -Args '%rootpath%'"
  10. echo;%info%
  11. pause
  12. exit
  13. #>
  14. Add-Type -TypeDefinition @'
  15. using System;
  16. using System.Collections.Generic;
  17. using System.Runtime.InteropServices;
  18. public static class ExpDir
  19. {
  20.     [DllImport("Shlwapi.dll", CharSet = CharSet.Unicode)]
  21.     public static extern int StrCmpLogicalW(string p1, string p2);
  22.     public static string[] Sort(string[] f)
  23.     {
  24.         Array.Sort(f, StrCmpLogicalW);
  25.         return f;
  26.     }  
  27. }
  28. '@;
  29. $outfile=$args[0]+'\'+(gi -liter $args[0]).Name+'.csv';
  30. $files=@(dir -liter $args[0]|?{($_.name -match '^data\d*\.0$') -and ($_ -is [System.IO.FileInfo])});
  31. $list=[ExpDir]::Sort($files);
  32. [System.Collections.ArrayList]$s=@();
  33. $max=0;
  34. for($i=0;$i -lt $list.count;$i++){
  35.     $text=[IO.File]::ReadAllLines(($args[0]+'\'+$list[$i]),[Text.Encoding]::Default);
  36.     if($text.count -ge $max){$max=$text.count};
  37.     if($i -eq 0){
  38.         [void]$s.add($text);
  39.     }else{
  40.         [System.Collections.ArrayList]$t=@();
  41.         for($j=0;$j -lt $text.count;$j++){
  42.             [void]$t.add($text[$j].split(',')[1]);
  43.         };
  44.         [void]$s.add($t);
  45.     };
  46. };
  47. [System.Collections.ArrayList]$ss=@();
  48. for($i=0;$i -lt $max;$i++){
  49.     [System.Collections.ArrayList]$tt=@();
  50.     for($j=0;$j -lt $s.count;$j++){
  51.         if($s[$j][$i] -eq $null){
  52.             [void]$tt.add(',');
  53.         }else{
  54.             [void]$tt.add($s[$j][$i]);
  55.         };
  56.     };
  57.     [void]$ss.add($($tt -join ','));
  58. };
  59. [IO.File]::WriteAllLines($outfile, $ss, [Text.Encoding]::Default);
复制代码

作者: Batcher    时间: 2019-8-29 08:17

回复 2# alan359


    建议找几个data文件打包压缩传上来,方便测试代码。
作者: xczxczxcz    时间: 2019-8-29 08:21

qq458609586 一键出最终excel文档。
作者: alan359    时间: 2019-8-29 08:50

回复 4# Batcher


   已上传数据,因为 .0文件上传不成功,扩展名修改为.txt文件
作者: flashercs    时间: 2019-8-29 09:51

joinColumns.bat
  1. <#*,:&cls
  2. @echo off
  3. pushd "%~dp0"
  4. Powershell -NoProfile -ExecutionPolicy RemoteSigned -Command ". ([ScriptBlock]::Create((Get-Content -LiteralPath \"%~0\" -ReadCount 0 | Out-String ))) "
  5. popd
  6. pause
  7. exit /b
  8. #>
  9. $outfile = Join-Path -Path ($pwd.Path) -ChildPath "$($pwd.Path|Split-Path -Leaf).xlsx"
  10. try {
  11.   $oExcelApp = New-Object -ComObject Excel.Application
  12. }
  13. catch {
  14.   try {
  15.     $oExcelApp = New-Object -ComObject ET.Application
  16.   }
  17.   catch {
  18.     throw
  19.   }
  20. }
  21. function Open-Text {
  22.   param (
  23.     [string]$Path
  24.   )
  25.   try {
  26.     $oExcelApp.Workbooks.OpenText($Path, 936, 1, 1, -4142, $false, $false, $false, $true, $false, $false, $null, @(@(1, 2), @(2, 2)))
  27.     return $true
  28.   }
  29.   catch {
  30.     return $false
  31.   }
  32. }
  33. try {
  34.   $oExcelApp.AutomationSecurity = 3
  35.   $oExcelApp.DisplayAlerts = $false
  36.   $oExcelApp.Interactive = $false
  37.   $oExcelApp.Visible = $false
  38.   # open data.0 as the base workbook
  39.   
  40.   if (Open-Text -Path (Join-Path -Path $pwd.Path -ChildPath "data.0")) {
  41.     $oWorkbook = $oExcelApp.Workbooks.Item("data.0")
  42.     $oWorksheet = $oWorkbook.Worksheets.Item(1)
  43.   }
  44.   else {
  45.     Write-Error -Message "Can't open data.0"
  46.     throw
  47.   }
  48.   
  49.   Convert-Path "data?*.0" | Sort-Object -Property { (Split-Path $_ -Leaf).Remove(0, 4).Split(".")[0] -as [int] } | ForEach-Object -Begin {
  50.     $column = 3
  51.   } -Process {
  52.     if ( Open-Text -Path $_) {
  53.       $oWorkbook1 = $oExcelApp.Workbooks.Item((Split-Path $_ -Leaf))
  54.       $oWorkbook1.Worksheets.Item(1).UsedRange.Columns.Item(2).Copy($oWorksheet.Cells.Item(1, $column++))
  55.       $oWorkbook1.Close()
  56.       Write-Host "Add $_ success" -ForegroundColor Green
  57.     }
  58.     else {
  59.       Write-Error -Message "Can't open $_"
  60.     }
  61.   } -End {
  62.     $oWorkbook.SaveAs($outfile, 51, $null, $null, $false, $false, 3, 2, $false, $null, $null, $true)
  63.   }
  64. }
  65. catch {
  66.   $_ | Out-String | Write-Host -ForegroundColor Red
  67. }
  68. finally {
  69.   $oExcelApp.Workbooks.Close()
  70.   $oExcelApp.Quit()
  71.   [void][System.Runtime.InteropServices.Marshal]::ReleaseComObject($oExcelApp)
  72.   Remove-Variable oExcelApp
  73. }
复制代码

作者: cfwyy77_bat    时间: 2019-8-29 10:21

如果楼主要求的结果不指定为 xlsx的话,可以把结果输出为CSV格式,其实输入的就是CSV格式(PS:windows下csv默认关联是用excel打开的
如果原文件数量不多,而且碰巧有类Bash环境,或者有以下用到的 windows下的第三方程序的话,下面的思路可以参考,只是思路,这里没有达到楼主的要求,仅供参考。
  1. ls *.txt | xargs paste -d, | cut -d, -f1,2,4,6,8
复制代码
这里假设有原4个文件,paste合并后取第一列及偶数列即可。
作者: alan359    时间: 2019-8-29 10:33

回复 8# cfwyy77_bat


    不要求xls文件,csv没问题的
作者: terse    时间: 2019-8-29 20:53

  1. @set @i=0 /* & @echo off & dir /b/a-d/on *.0 |cscript -nologo -e:jscript "%~0" & pause & exit */
  2. var fso=new ActiveXObject("Scripting.FileSystemObject");
  3. var filename=fso.GetFolder(".");
  4. filename +=  "\\" +fso.GetFolder(".").name + ".xlsx";
  5. var oXL = new ActiveXObject("Excel.Application");
  6. oXL.visible = true;
  7. var excel = oXL.Workbooks.Add;
  8. excel.Worksheets(1).Activate;
  9. var t = true, n = 1, m = 2, f =  fso.GetFolder(".");
  10. while (!WScript.StdIn.AtEndOfStream){
  11.       var  file = WScript.StdIn.Readline();
  12.       var arr =  fso.OpenTextFile(file,1).ReadAll().replace(/^\r\n/gm, "").replace(/\r\n$/gm,"").split("\r\n");
  13.       if (t) {
  14.            for(i = 0, len = arr.length; i < len; i++ ){
  15.                var ar = arr[i].split(",");
  16.                excel.Worksheets(1).Cells(i+1,n).value = '' + ar[0];
  17.                excel.Worksheets(1).Cells(i+1,m).value = '' + ar[1];
  18.            };
  19.                t = false, n += m;
  20.       };
  21.           else {
  22.              for(i = 0, len = arr.length; i < len; i++ ){
  23.                  var ar = arr[i].split(",");
  24.                  excel.Worksheets(1).Cells(i+1,n).value = '' + ar[1];
  25.              };
  26.              n++;
  27.       };
  28. }
  29. excel.Worksheets(1).SaveAs(filename);
  30. excel.Close();
  31. oXL.Application.Quit();
复制代码

作者: xczxczxcz    时间: 2019-8-29 22:16

csv是不是太简单了!exce才算吧。各种字体,线型,边框,格子大小,等等用excel是一次全搞定了,出来就是ok文档。




欢迎光临 批处理之家 (http://www.bathome.net/) Powered by Discuz! 7.2