使用C#将Excel表格内容写入控制台时,输出格式不符合人类阅读的格式要求。

3

我正在尝试读取一个Excel表格并将内容显示到控制台。代码如下:

  FileStream fileStream = new FileStream(@"E:\USERS\MyWorkbook.xlsx", FileMode.Open, FileAccess.Read);
  byte[] byteCode = new byte[fileStream.Length];
  fileStream.Read(byteCode, 0, (int)fileStream.Length);            
  foreach (var byteValue in byteCode)
  {
      Console.Write(Convert.ToChar(byteValue));
  }
  Console.ReadLine();

输出结果为:

PK♥♦¶ ♠ ! bî?h^☺ ?♦ ‼☻[Content_Types].xml ¢♦☻(  ☻

¬?ENA0►E÷HüCä-Jܲ5í?Ç↕*Q>AÄ?ƪc[?iiÿ??û►B¡§j7±↕IÜ{2ñIh²nm¶??Æ»R♀??EAU^←7/>ÅÇ ì%¿↨↓?rZYï ¶←@1↓__?f? ?q·AR4DáAJ¬→h§▬>?a?UÇV◄ßÆ1♀ªZ"9EUAàNV_◄8EcO►aÑ‼Oji){^óa-I♦ ?"{Ü▬v^¥P!XS)bR1rú?K_s(,3O`▬_§ïßeÖ↔♦»ß1æ►@(?a?sí?►[í?☼öB·LA?F←I↔"fKlk↑--¿$♣?A pN$å

有什么问题吗?


只需按照这个教程,它会帮助您完成操作:https://bytescout.com/products/developer/spreadsheetsdk/read-write-excel.html - KARAN
如果你需要以二进制形式读取文件,你必须使用 Excel 对象代替,有很多示例可供参考。 - user3131905
上面的链接是一个不好的做法(调用GC并将对象设置为null)。 - user3131905
因为这不是以编程方式读取Excel文件的方法...你的问题中已经给出了一些好的解决方案.. - Moumit
3个回答

6

借助于Oledb(对象链接和嵌入式数据库)。OLE DB是微软访问不同数据源的战略性低级应用程序接口(API)。

OLE DB中的对象主要包括数据源对象、会话对象、命令对象和行集对象。使用OLE DB的应用程序将使用以下请求序列:

  1. 初始化OLE。
  2. 连接到数据源。
  3. 发出命令。
  4. 处理结果。
  5. 释放数据源对象并取消初始化OLE。

这里是以前stackoverflow答案的链接,介绍如何使用oledb从Excel访问数据。

如何使用c#从Excel文件读取数据

这是示例代码

string path = @"E:\USERS\MyWorkbook.xlsx";
//Create connection string to Excel work book
string excelConString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;Persist Security Info=False";

OleDbConnection excelCon = new OleDbConnection(excelConString);

excelCon.Open();

DataTable dtsheet = new DataTable();

dtsheet = excelCon.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });    

foreach (DataRow row in dtExcelSheet.Rows)
{ 
    Query = string.Format("Select * from [{0}]", row["TABLE_NAME"].ToString());
    //Create OleDbCommand to fetch data from Excel
    OleDbCommand cmd = new OleDbCommand(Query, excelCon);
    DataSet ds = new DataSet();
    OleDbDataAdapter oda = new OleDbDataAdapter(Query, excelCon);
    excelCon.Close();
    oda.Fill(ds);
    DataTable Exceldt = ds.Tables[0];

   foreach (DataRow dr in Exceldt.Rows)
   {
      //code to display
   }
}

你能否提供一些演示代码,展示它是如何解决这个问题的? - Moumit
1
@Moumit 我已经编辑了帖子并附上了示例代码。你可以看一下。 - Fanjo Lama

4
您可能需要查看Office互操作对象模型或使用oledb适配器。
Codeproject在这里提供了一些关于对象模型的好资源http://www.codeproject.com/Tips/696864/Working-with-Excel-using-Csharp 而且之前的stackoverflow答案介绍了如何使用oledb连接来查询数据https://dev59.com/-nVD5IYBdhLWcg3wVJ8b#16051 以下是一些使用Office对象的示例代码:
using Excel = Microsoft.Office.Interop.Excel;

        Excel.Application app = new Excel.Application();
        Excel.Workbook wb = app.Workbooks.Open("path to a workbook");
        Excel.Worksheet sheet = (Excel.Worksheet)wb.Sheets[1];
        int lastrow = sheet.UsedRange.Rows.Count;
        int lastcol = sheet.UsedRange.Rows.Count;

        Excel.Range c1;
        Excel.Range c2;

        for (int i = 1; i <= lastrow; i++)
        {
            c1 = (Excel.Range)sheet.Cells[i, 1];
            c2 = (Excel.Range)sheet.Cells[i, lastcol];
            Excel.Range range = sheet.Range[c1, c2];

            foreach(Object o in (System.Array)range.Value)
            {
                if (o != null)
                {
                    Console.Write(o.ToString());
                }
            }
            Console.WriteLine();
        }
        Console.ReadLine();

加1和XLM读取版本 https://msdn.microsoft.com/zh-cn/library/office/cc823095.aspx - user3131905
请您提供一些演示代码,以展示它如何是问题的解决方案。 - Moumit

3

像其他人提到的那样,你可以考虑使用Office互操作对象。将Microsoft.Office.Interop.Excel添加为项目引用,通常可以在以下目录找到该dll:

C:\Program Files (x86)\Microsoft Visual Studio 12.0\Visual Studio Tools for Office\PIA\Office15

这是一段代码,可能有助于你想做的事情,我已经添加了注释,以帮助你更好地理解每一行:

Excel.Application xlApp = new Excel.Application();
//Points to the excel path
Excel.Workbook xlWorkbook = xlApp.Workbooks.Open(@"E:\USERS\MyWorkbook.xlsx");    
//Sheets[1] = First worksheet, modify this according to your need
Excel.Worksheet xlWorksheet = xlWorkbook.Sheets[1];    
//UsedRange means the range of cells that has contents (are being used).
Excel.Range xlRange = xlWorksheet.UsedRange;

int rowCount = xlRange.Rows.Count;
int colCount = xlRange.Columns.Count;

for (int i = 1; i <= rowCount; i++)
    {
        for (int j = 1; j <= colCount; j++)
        {
            var cellContent = xlWorksheet.Cells[i, j].Value;
            //To prevent exceptions due to null reference         
            if (cellContent != null)
            {
                Console.WriteLine(cellContent.ToString());
            }                  
        }
    }              

首先,您使用.UsedRange来确定包含内容的最大行和列数。然后,您只需进行嵌套循环并使用Console.WriteLine在每个单元格中显示内容(就像您所想的那样)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接