Skip to content

Instantly share code, notes, and snippets.

@Krizzzn
Last active August 29, 2015 14:18
Show Gist options
  • Select an option

  • Save Krizzzn/0c714d337c5c3c0e7708 to your computer and use it in GitHub Desktop.

Select an option

Save Krizzzn/0c714d337c5c3c0e7708 to your computer and use it in GitHub Desktop.
A scriptcs file for opening a bunch of excel files, reading the first column and putting it into a txt file.
// A scriptcs (http://scriptcs.net/) file for opening a bunch of excel files, reading the first column and putting the content into a txt file.
//
// Needs the Microsoft.Office.Interop.Excel.dll to be in the same directory as the script.
// Copy it there by using `>copy C:\Windows\assembly\GAC_MSIL\Microsoft.Office.Interop.Excel\14.0.0.0__71e9bce111e9429c\Microsoft.Office.Interop.Excel.dll`
#r "Microsoft.Office.Interop.Excel.dll"
using System.IO;
using Microsoft.Office.Interop.Excel;
using System.Linq;
public static string[] FirstColumn(string filename, Microsoft.Office.Interop.Excel.Application xlsApp)
{
Workbook wb = xlsApp.Workbooks.Open(filename,
0, true, 5, "", "", true, XlPlatform.xlWindows, "\t", false, false, 0, true);
Sheets sheets = wb.Worksheets;
Worksheet ws = (Worksheet)sheets.get_Item(1);
Range firstColumn = (Range)ws.UsedRange.Columns[1];
System.Array myvalues = (System.Array)firstColumn.Cells.Value;
string[] strArray = myvalues.OfType<object>().Select(o => o.ToString()).ToArray();
wb.Close();
return strArray;
}
Microsoft.Office.Interop.Excel.Application xlsApp = new Microsoft.Office.Interop.Excel.Application();
//Displays Excel so you can see what is happening
//xlsApp.Visible = true;
if (xlsApp == null)
throw new Exception("EXCEL could not be started. Check that your office installation and project references are correct.");
if (File.Exists("out.list"))
File.Delete("out.list");
foreach (string file in Directory.EnumerateFiles(@"C:\path_full_of_xls_files\", "*.xls")) {
var results = FirstColumn(file, xlsApp);
Console.WriteLine(file);
File.AppendAllLines("out.list", results);
}
xlsApp.Quit();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment