转自
http://hi.baidu.com/david_jdai/item/d3bf00262cd904140975085d
koogra是一个.net平台下开源的excel读取程序,可以在开源社区下载它。使用它我们无需office就可以读取excel文件。尽管这个程序已经停止了更新,但是它还是很好用的。下面介绍怎么使用它。
下载到该程序的源代码,编译生成Net.SourceForge.Koogra.dll。在项目中引用该dll,using Net.SourceForge.Koogra.Excel;
Workbook wb = new Workbook(path);path是文件的物理路径,这可以创建一个excel文件对象
Worksheet xSheet = xBook.Sheets[0];引用Workbook 的工作表
xBook.Sheets.GetByName(string)还可以通过这个方法获取对Workbook 工作表的引用。
xBook.Sheets.Rows[i]对excel行的引用
xBook.Sheets.Rows[i].Cells[i]对单元格的引用
xSheet.Rows.FirstRow 首行的行号,从0开始
xSheet.Rows.LastRow 尾行的行号,对于中间有空行,可以用xSheet.Rows[i]==null判断
Cells对应的也有FirstCol,LastCol属性,对于Cells为NUll的情况下不能使用Cells.Value
下面是一个例子:
/// <summary>
/// This method just exercises the excel workbook data.
/// </summary>
/// <param name="path">The path to the workbook.</param>
private Workbook DumpWorkbookToConsole(string path)
{
// print the path
Console.WriteLine(path);
// construct our workbook
Workbook wb = new Workbook(path);
// dump the worksheet data
foreach(Worksheet ws in wb.Sheets)
{
Console.Write("Sheet is ");
Console.Write(ws.Name);
Console.Write(" First row is: ");
Console.Write(ws.Rows.FirstRow);
Console.Write(" Last row is: ");
Console.WriteLine(ws.Rows.LastRow);
// dump cell data
for(int r = ws.Rows.FirstRow; r <= ws.Rows.LastRow; ++r)
{
Row row = ws.Rows[(ushort)r];
if(row != null)
{
Console.Write("Row: ");
Console.Write(r);
Console.Write(" First Col: ");
Console.Write(row.Cells.FirstCol);
Console.Write(" Last Col: ");
Console.WriteLine(row.Cells.LastCol);
for(int c = row.Cells.FirstCol; c <= row.Cells.LastCol; ++c)
{
Cell cell = row.Cells[(byte)c];
Console.Write("Col: ");
Console.Write(c);
if(cell != null)
{
Console.Write(" Value: ");
Console.Write(cell.Value);
Console.Write(" Formatted Value: ");
Console.WriteLine(cell.FormattedValue());
}
else
Console.WriteLine(" null");
}
}
}
}
return wb;
}
更多的功能有待大家去发掘,呵呵~反正是C#写的,源代码也有,慢慢看吧。此外另一个开源的东东:myxls支持excel的读写,现在依然在更新,也是很不错的。
koogra一些修正:
1. 修正中文工作表名乱码的BUG
將 \Excel\Records\BoundSheetRecord.cs 34~38行
ushort nameLen = reader.ReadUInt16();
StringBuilder nb = new StringBuilder(nameLen);
nb.Append(new string(reader.ReadChars(nameLen)));
_name = nb.ToString();
改成
ushort nameLen = (ushort)reader.ReadByte();
bool compressed = (reader.ReadByte() * 0x01) == 0;
if (!compressed) {
nameLen *= 2;
}
byte[] charBytes = reader.ReadBytes(nameLen);
if (compressed) {
//decompress
byte[] wideBytes = new byte[charBytes.Length * 2];
for (int i = 0; i < charBytes.Length; i++)
wideBytes[2 * i] = charBytes[i];
charBytes = wideBytes;
}
_name = new string(Encoding.Unicode.GetChars(charBytes));
2.调整日期的默认格式
讀取 excel 裏的日期資料,譬如 2007/3/5
用cell.FormattedValue() 會取得字串 "3/5/07"
那通常不是我想要的,所以我修改了原本的 Cell.cs
public string FormattedValue() {
...
...
// get the format string
string formatString = format.FormatValue;
+if (formatString == "M/D/YY") {
+ formatString = "yyyy/MM/dd";
+}
-----------------本bloger的话-------------------
今天发现koogra已经更新到3.1.1版。只有dll文件。不过可以用reflector反编译得到源代码。
项目地址:koogra