C# 使用 ExcelLibrary 读写 Excel 文件

ExcelLibrary 是一个比较精致的 Excel 读写组件,还是由国人开发的,下载地址:http://code.google.com/p/excellibrary/。可以读写 xls 和 xlsx 格式的 Excel。支持简单的公式,可插入图片,对于格式的设置也不是很丰富,可设置单元格宽度,数据格式化显示。对字体,前景、背景色进行设置是它的局限性。虽比不上 NPOI,但作为小巧的用来读写纯数据内容的 Excel 还是很高效的。

具体的例子,可以考看它的测试代码:ExcelLibrary.Test\SimpleTest.cs。这里

写 Excel 文件:

using System;
using ExcelLibrary.SpreadSheet;
 
class ExcelLibraryTest
{
    public static void Main(string[] args)
    {
 
        Workbook workbook = new Workbook();
        Worksheet worksheet = new Worksheet("Persons");
 
        worksheet.Cells[0, 0] = new Cell("ID");
        worksheet.Cells[0, 1] = new Cell("Name");
        worksheet.Cells[0, 2] = new Cell("Age");
     // 设置列宽
     worksheet.Cells.ColumnWidth[(ushort)0] = 3200;
     worksheet.Cells.ColumnWidth[(ushort)1] = 3200;   
     worksheet.Cells.ColumnWidth[(ushort)2] = 3200;   
            
     worksheet.Cells[1, 0] = new Cell("1"); 
       worksheet.Cells[1, 1] = new Cell("Unmi"); 
     worksheet.Cells[1, 2] = new Cell("xxx"); 

     //可以下列方法设置额外的信息 //worksheet.AddPicture; worksheet.ExtractPicture;worksheet.Cells.ColumnWidth  
     workbook.Worksheets.Add(worksheet); 
     workbook.Save(@"c:\test.xls"); } }
读 Excel 文件:

using System;
using System.IO;
using ExcelLibrary.SpreadSheet;
 
class ExcelLibraryTest
{
    public static void Main(string[] args)
    {
        FileStream fileStream = new FileStream(@"c:\test.xls", FileMode.Open);
 
        Workbook workbook = Workbook.Load(fileStream);
 
        //也可以直接传个文件名,但会报出 Stream was not writable.异常
        //Workbook workbook = Workbook.Load(@"c:\test.xls");
 
        Worksheet worksheet = workbook.Worksheets[0];
 
        for (int i = 0; i <= worksheet.Cells.LastRowIndex; i++)
        {
            for (int j = 0; j <= worksheet.Cells.LastColIndex; j++)
            {
                Console.Write(worksheet.Cells[i, j].Value);
                if (j < worksheet.Cells.LastColIndex)
                    Console.Write(", ");
            }
            Console.WriteLine();
        }
 
        fileStream.Close();
 
        Console.Write("Press any key to continue . . . ");
        Console.ReadKey(true);
    }
}

上面代码中提到,用 Workbook.Load(filename) 会报 Stream was not writable,问题原因应该是说试图去写一个不可写的流。从这行代码出发跟踪下就会发现,它是用以下语句打开文件的:

        public static Workbook Load(string file)
        {
            return Load(File.OpenRead(file));
        }

OpenRead() 就假定了是一个只读的东西,好像无可厚非,就想读数据吗,写文件不是有 Workbook.Save(filename) 方法吗?可是再往下,会转到方法 CompoundDocument.CompoundDocument(Stream stream, FileHeader header),其中的:

            this.FileStorage = stream;
            this.Reader = new BinaryReader(this.FileStorage);
            this.Writer = new BinaryWriter(this.FileStorage, Encoding.Unicode);

动机并非那么单纯,这里的 FilteStorage 或者 stream 就是前面用 File.OpenRead(file) 得到的,试图以此来获得一个可写的 BinaryWriter,而这个 stream 的 CanWrite 属性是 false。

解决的办法有两,要么打开一个可写的文件流,不过毕竟是用 Workbook.Save() 方法,所以应该在创建 BinaryWriter 前作个判断,如下:

            if(this.FileStorage.CanWrite)
            {
                    this.Writer = new BinaryWriter(this.FileStorage, Encoding.Unicode);
            }

这样做的话还有一个好处,当用 Workbook.Load(fileStream); 直接 Load 一个文件流时也是必须这样判断的,例如 HTTP 上传 Excel 文件时要读出其中内容,我们能拿到的 FileUpload.FileContent 是一个 HttpInputStream,你肯定无法由它来创建一个可写的 BinaryWriter 的。

加完这个是否可写的判断,重新编译成你要用的动态库就行啦。另外,对 ExcelLibrary 还有个小小的改造是 DataSetHelper 类,能用来由 Excel 生成 DataSet 或 DataTable,应该再有几个重载方法会方便些:

public static DataTable CreateDataTable(String filePath, int sheetIndex)
public static DataTable CreateDataTable(Stream stream, String sheetName)
public static DataTable CreateDataTable(Stream stream, int sheetIndex)
public static DataSet CreateDataSet(Stream stream)

最后,项目好像很久没怎么维护了,希望加强格式,风格上的控制。

参考:1. Asp.net利用ExcelLibrary输出EXCEL
        2. Excel Reader Create, read and modify Excel *.xls files in pure C# without COM interop




  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
C#读写 Excel 文件可以使用 Microsoft Office 应用程序或开源库。以下是使用 Microsoft Office 应用程序的示例代码: ```csharp using System; using System.Data; using System.Data.OleDb; class ExcelReadWrite { static void Main() { string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=example.xlsx;Extended Properties='Excel 12.0;HDR=YES;'"; // 读取数据 using (OleDbConnection connection = new OleDbConnection(connectionString)) { connection.Open(); OleDbCommand command = new OleDbCommand("SELECT * FROM [Sheet1$]", connection); OleDbDataAdapter adapter = new OleDbDataAdapter(command); DataTable dataTable = new DataTable(); adapter.Fill(dataTable); foreach (DataRow row in dataTable.Rows) { Console.WriteLine(row["Column1"].ToString() + "\t" + row["Column2"].ToString()); } } // 写入数据 using (OleDbConnection connection = new OleDbConnection(connectionString)) { connection.Open(); OleDbCommand command = new OleDbCommand("INSERT INTO [Sheet1$] ([Column1], [Column2]) VALUES (@Column1, @Column2)", connection); command.Parameters.AddWithValue("@Column1", "Value1"); command.Parameters.AddWithValue("@Column2", "Value2"); int rowsAffected = command.ExecuteNonQuery(); Console.WriteLine(rowsAffected.ToString() + " rows inserted."); } } } ``` 以上代码使用 `OleDbConnection` 和 `OleDbCommand` 类连接到 Excel 文件,并读取或写入数据。需要注意的是,这种方法需要安装 Microsoft Office 应用程序才能工作,且需要保证 Excel 文件的格式正确。 开源库方面,可以使用 `EPPlus` 或 `NPOI` 库来读写 Excel 文件。以下是使用 `EPPlus` 库的示例代码: ```csharp using System; using OfficeOpenXml; class ExcelReadWrite { static void Main() { string filePath = @"example.xlsx"; // 读取数据 using (ExcelPackage package = new ExcelPackage(new System.IO.FileInfo(filePath))) { ExcelWorksheet worksheet = package.Workbook.Worksheets[1]; for (int row = 1; row <= worksheet.Dimension.Rows; row++) { Console.WriteLine(worksheet.Cells[row, 1].Value.ToString() + "\t" + worksheet.Cells[row, 2].Value.ToString()); } } // 写入数据 using (ExcelPackage package = new ExcelPackage(new System.IO.FileInfo(filePath))) { ExcelWorksheet worksheet = package.Workbook.Worksheets[1]; worksheet.Cells[worksheet.Dimension.Rows + 1, 1].Value = "Value1"; worksheet.Cells[worksheet.Dimension.Rows + 1, 2].Value = "Value2"; package.Save(); } } } ``` 以上代码使用 `ExcelPackage` 类连接到 Excel 文件,并读取或写入数据。需要注意的是,这种方法需要安装 `EPPlus` 库才能工作。 综上所述,读写 Excel 文件有多种方法,可以根据具体情况选择合适的方法。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值