2013-07-03 61 views
0

我想上传一个Excel工作表并将其保存为文本文件,然后从该文本文件中读取。我的一个朋友在他的应用程序中实现了这个功能,并且工作正常。我只是复制他的代码,但它没有适当地与我合作。它保存Excel工作表为文本文件,但是当我打开文本文件时,我发现了数据损坏和大量的Unicode或奇怪的符号与许多不必要的线路,如:如何将此Excel工作表保存为asp.net中的文本文件(.txt)?

  ;   þÿÿÿ þÿÿÿ : 

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

ASP.NET代码:

<asp:FileUpload ID="Upload" runat="server" /> 
<asp:Button ID="btn_upload" runat="server" Text="Upload" OnClick="UploadButton_Click" /> 
<asp:Label ID="Label1" runat="server" /> 

C#代码:

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."; 

     } 
    } 

我使用ASP.NET 4与C#,所以请你告诉我,我应该能够在Excel工作表保存为txt文件,然后从它读?

+0

同样的事情发生当你拿一个Excel文档并将扩展名改为txt时。您需要一个实际能够打开/读取Office文档的扩展,然后将内容解析为简单文本。无论如何,最终的实现将需要比你在这里更复杂。 – MadHenchbot

+3

请注意答案,但不要使用Office Interop来实现它们。从ASP.NET或其他服务器技术使用Office Interop是一个可怕的想法。这些API被编写用于桌面应用程序,用于自动化Office(一套桌面应用程序)。服务器应用程序在许多方面有所不同,因此在其中使用Office Interop是非常非常糟糕的主意。它也不受Microsoft的支持,并可能违反您的Office许可证。请参阅[服务器端自动化Office的注意事项](http://support.microsoft.com/kb/257757) –

回答

2

不能以文本格式保存Excel文件,你需要使用.csv延伸,而不是使用XLSX或XLS,并将其保存为.txt

5

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

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

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

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

如果你坚持支持.xlsx文件,有一种方法。 Office XML文件格式是一种开放和公开的格式,允许您按自己的喜好操纵它。

你将需要:

  1. Download The Open XML SDK

  2. Carefully read the documentation

在你的情况,你可能会想访问特定的单元格的值,读取其内容,然后将它们流入一个新文件。

上述文档提供下面的代码片断为一个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; 
} 

从那里,可以做任何你与单元格值喜欢=)

相关问题