Skip to content

Instantly share code, notes, and snippets.

@nissuk
Created April 26, 2012 07:05
Show Gist options
  • Save nissuk/2497032 to your computer and use it in GitHub Desktop.
Save nissuk/2497032 to your computer and use it in GitHub Desktop.
C#: Excelの読み込み
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.OleDb;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
// Microsoft.Jet.OLEDB.4.0がx64に対応していないのでx86でビルドして下さい。
var filename = @"E:\test\Book1.xls";
/*
* 「Sheet1」に下記の内容が入っているものとします(例ではtab-separated)。
* id name birthday
* 1 fooさん 1990/12/31
* 2 barさん 2001/1/1
*/
var builder = new OleDbConnectionStringBuilder() {
{ "Provider", "Microsoft.Jet.OLEDB.4.0" },
{ "Extended Properties", "Excel 8.0" },
{ "Data Source", filename }
};
var sheetName = "[Sheet1$]";
using (var a = new OleDbDataAdapter("SELECT * FROM " + sheetName, builder.ToString())) {
var set = new DataSet("Data");
a.FillSchema(set, SchemaType.Source, sheetName);
a.Fill(set, sheetName);
foreach (DataRow row in set.Tables[sheetName].Rows) {
// id: 0001, name: fooさん, birth: 1999-12-31 のように表示
Console.WriteLine("id: {0:04}, name: {1}, birth: {2:yyyy-MM-dd}", row["id"], row["name"], row["birthday"]);
// 手っ取り早くCSV行として表示(.NET 4ならToArray()不要)
Console.WriteLine(string.Join(",", row.ItemArray.Select(x => "\"" + x + "\"").ToArray()));
}
}
}
}
}
@nissuk
Copy link
Author

nissuk commented Apr 28, 2012

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment