C# 如何在asp.net中将此Excel工作表保存为文本文件(.txt)?

C# 如何在asp.net中将此Excel工作表保存为文本文件(.txt)?,c#,asp.net,excel,C#,Asp.net,Excel,我正试图上传一张excel表格,并将其保存为文本文件,然后从该文本文件中读取。我的一个朋友在他的应用程序中实现了这样的功能,它工作得很好。我只是复制了他的代码,但它不能正常工作。它将excel工作表保存为文本文件,但当我打开文本文件时,发现数据已损坏,并且有许多Unicode或奇怪的符号,其中包含许多不必要的行,例如: ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ ASP.NET代码: C代码: 我使用的是ASP.NET4和C,所以你能告诉我应该如何将Excel表格保存为txt文件,然后从中读取吗

我正试图上传一张excel表格,并将其保存为文本文件,然后从该文本文件中读取。我的一个朋友在他的应用程序中实现了这样的功能,它工作得很好。我只是复制了他的代码,但它不能正常工作。它将excel工作表保存为文本文件,但当我打开文本文件时,发现数据已损坏,并且有许多Unicode或奇怪的符号,其中包含许多不必要的行,例如:

ÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿÿ

ASP.NET代码:

C代码:


我使用的是ASP.NET4和C,所以你能告诉我应该如何将Excel表格保存为txt文件,然后从中读取吗

您不能以文本格式保存Excel文件,您需要使用.csv扩展名而不是xlsx或xls,并将其另存为.txt。

为了使Excel文件在文本编辑器中可读,必须将其转换为csv文件格式。这是因为.xlsx Excel文档2007+是复杂的XML层次结构。如果您想了解.xlsx文件的真正组成部分,请将其扩展名更改为.zip,然后将其解压缩

因此,您不能简单地将.xlsx文件的扩展名更改为.txt或.csv,并期望它在文本编辑器中可读。您必须从一开始就以这种格式保存文件

在Excel中,将电子表格另存为.csv而不是.xlsx,然后您可以立即将其打开到文本编辑器中!如果你真的想,你甚至可以把扩展名改成.txt

如果您不告诉Excel将其自身保存为纯文本而不是其正常的XML结构,那么所有这些都不会起作用

如果您坚持支持.xlsx文件,有一种方法。Office XML文件格式是一种开放的公共格式,允许您随意操作它

您需要:

在您的情况下,您可能需要访问特定的单元格值,读取其内容,然后将其流式传输到新文件中

上述文档提供了以下代码段,用于访问Excel文档中的单元格值:

public static string XLGetCellValue(string fileName, string sheetName, string addressName)
{
   const string worksheetSchema = "http://schemas.openxmlformats.org/spreadsheetml/2006/main";
   const string sharedStringSchema = "http://schemas.openxmlformats.org/spreadsheetml/2006/main";

   string cellValue = null;

   //  Retrieve the stream containing the requested
   //  worksheet's info.
   using (SpreadsheetDocument xlDoc = SpreadsheetDocument.Open(fileName, false))
   {
      //  Get the main document part (workbook.xml).
      XmlDocument doc = new XmlDocument();
      doc.Load(xlDoc.WorkbookPart.GetStream());

      //  Create a namespace manager, so you can search.
      //  Add a prefix (d) for the default namespace.
      NameTable nt = new NameTable();
      XmlNamespaceManager nsManager = new XmlNamespaceManager(nt);
      nsManager.AddNamespace("d", worksheetSchema);
      nsManager.AddNamespace("s", sharedStringSchema);

      string searchString = string.Format("//d:sheet[@name='{0}']", sheetName);
      XmlNode sheetNode = doc.SelectSingleNode(searchString, nsManager);
      if (sheetNode != null)
      {
         //  Get the relId attribute.
          XmlAttribute relationAttribute = sheetNode.Attributes["r:id"];
         if (relationAttribute != null)
         {
            string relId = relationAttribute.Value;
            //  Load the contents of the workbook.
            XmlDocument sheetDoc = new XmlDocument(nt);
            sheetDoc.Load(xlDoc.WorkbookPart.GetPartById(relId).GetStream());

            XmlNode cellNode = sheetDoc.SelectSingleNode(string.Format("//d:sheetData/d:row/d:c[@r='{0}']", addressName), nsManager);
            if (cellNode != null)
            {
               XmlAttribute typeAttr = cellNode.Attributes["t"];
               string cellType = string.Empty;
               if (typeAttr != null)
               {
                  cellType = typeAttr.Value;
               }

               XmlNode valueNode = cellNode.SelectSingleNode("d:v", nsManager);
               if (valueNode != null)
               {
                  cellValue = valueNode.InnerText;
               }
               if (cellType == "b")
               {
                  if (cellValue == "1")
                  {
                     cellValue = "TRUE";
                  }
                  else
                  {
                     cellValue = "FALSE";
                  }
               }
               else if (cellType == "s")
               {
                   if (xlDoc.WorkbookPart.SharedStringTablePart != null)
                   {
                      XmlDocument stringDoc = new XmlDocument(nt);
                      stringDoc.Load(xlDoc.WorkbookPart.SharedStringTablePart.GetStream());
                      //  Add the string schema to the namespace manager.
                      nsManager.AddNamespace("s", sharedStringSchema);

                      int requestedString = Convert.ToInt32(cellValue);
                      string strSearch = string.Format("//s:sst/s:si[{0}]", requestedString + 1);
                      XmlNode stringNode = stringDoc.SelectSingleNode(strSearch, nsManager);
                      if (stringNode != null)
                      {
                          cellValue = stringNode.InnerText;
                      }
                   }
                }
            }
         }
       }
   }
   return cellValue;
}

从那里,您可以对单元格值执行任何操作=

获取Excel文档并将扩展名更改为txt时,也会发生同样的情况。您需要一个能够打开/读取Office文档,然后将内容解析为简单文本的扩展。在任何情况下,最终的实现都需要比这里的要复杂得多。请注意答案,但不要使用Office Interop实现它们。从ASP.NET或其他服务器技术使用Office互操作是一个可怕的想法。这些API是为在桌面应用程序中使用而编写的,用于自动化Office一套桌面应用程序。服务器应用程序在许多方面都不同,因此在其中使用Office互操作是一个非常非常糟糕的主意。它也不受Microsoft支持,可能会违反您的Office许可证。看见
<asp:FileUpload ID="Upload" runat="server" />
<asp:Button ID="btn_upload" runat="server" Text="Upload" OnClick="UploadButton_Click" />
<asp:Label ID="Label1" runat="server" />
protected void UploadButton_Click(object sender, EventArgs e)
    {
        if (Upload.HasFile)
        {
            try
            {
                Upload.SaveAs(Server.MapPath("~/Files/Test_" + DateTime.Now.Year + "_" + DateTime.Now.Month + ".txt"));
                LabelUpload.Text = "Upload File Name: " + Upload.PostedFile.FileName + "<br>" + "Type: " + Upload.PostedFile.ContentType + " File Size: " + Upload.PostedFile.ContentLength + " kb<br>";

                string filename = Server.MapPath("~/Files/Test_" + DateTime.Now.Year + "_" + DateTime.Now.Month + ".txt");
                if (System.IO.File.Exists(filename))
                {
                    LabelUpload.Text = LabelUpload.Text + "Uploaded Successfully";
                }
            }
            catch (Exception ex)
            {
                Label1.Text = "Error: " + ex.Message.ToString();
            }
        }

        else
        {
            LabelUpload.Text = "Please select a file to upload.";

        }
    }
public static string XLGetCellValue(string fileName, string sheetName, string addressName)
{
   const string worksheetSchema = "http://schemas.openxmlformats.org/spreadsheetml/2006/main";
   const string sharedStringSchema = "http://schemas.openxmlformats.org/spreadsheetml/2006/main";

   string cellValue = null;

   //  Retrieve the stream containing the requested
   //  worksheet's info.
   using (SpreadsheetDocument xlDoc = SpreadsheetDocument.Open(fileName, false))
   {
      //  Get the main document part (workbook.xml).
      XmlDocument doc = new XmlDocument();
      doc.Load(xlDoc.WorkbookPart.GetStream());

      //  Create a namespace manager, so you can search.
      //  Add a prefix (d) for the default namespace.
      NameTable nt = new NameTable();
      XmlNamespaceManager nsManager = new XmlNamespaceManager(nt);
      nsManager.AddNamespace("d", worksheetSchema);
      nsManager.AddNamespace("s", sharedStringSchema);

      string searchString = string.Format("//d:sheet[@name='{0}']", sheetName);
      XmlNode sheetNode = doc.SelectSingleNode(searchString, nsManager);
      if (sheetNode != null)
      {
         //  Get the relId attribute.
          XmlAttribute relationAttribute = sheetNode.Attributes["r:id"];
         if (relationAttribute != null)
         {
            string relId = relationAttribute.Value;
            //  Load the contents of the workbook.
            XmlDocument sheetDoc = new XmlDocument(nt);
            sheetDoc.Load(xlDoc.WorkbookPart.GetPartById(relId).GetStream());

            XmlNode cellNode = sheetDoc.SelectSingleNode(string.Format("//d:sheetData/d:row/d:c[@r='{0}']", addressName), nsManager);
            if (cellNode != null)
            {
               XmlAttribute typeAttr = cellNode.Attributes["t"];
               string cellType = string.Empty;
               if (typeAttr != null)
               {
                  cellType = typeAttr.Value;
               }

               XmlNode valueNode = cellNode.SelectSingleNode("d:v", nsManager);
               if (valueNode != null)
               {
                  cellValue = valueNode.InnerText;
               }
               if (cellType == "b")
               {
                  if (cellValue == "1")
                  {
                     cellValue = "TRUE";
                  }
                  else
                  {
                     cellValue = "FALSE";
                  }
               }
               else if (cellType == "s")
               {
                   if (xlDoc.WorkbookPart.SharedStringTablePart != null)
                   {
                      XmlDocument stringDoc = new XmlDocument(nt);
                      stringDoc.Load(xlDoc.WorkbookPart.SharedStringTablePart.GetStream());
                      //  Add the string schema to the namespace manager.
                      nsManager.AddNamespace("s", sharedStringSchema);

                      int requestedString = Convert.ToInt32(cellValue);
                      string strSearch = string.Format("//s:sst/s:si[{0}]", requestedString + 1);
                      XmlNode stringNode = stringDoc.SelectSingleNode(strSearch, nsManager);
                      if (stringNode != null)
                      {
                          cellValue = stringNode.InnerText;
                      }
                   }
                }
            }
         }
       }
   }
   return cellValue;
}