从c#生成excel

时间:2018-03-08 13:47:26

标签: c# openxml

Hello Everyone我的代码有问题。当我尝试运行它时,我得到一个错误101590.这是我的代码,我尝试创建新的Excel文件并从a.xml文件中读取。我不知道我做错了什么,我试图按照我在网上发现的说明,但似乎我错过了一些东西。 C#:

public HttpResponseMessage PrintDevices()
{
    String path = $"{Folder}/{Properties.Settings.Default.Documents_Folder_Template}";
    String template = $"{path}/a.xml";
    StreamReader sr = File.OpenText(template);
    string strSheetData = sr.ReadToEnd();

    HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);

    using (MemoryStream output = new MemoryStream())
    {
        using (SpreadsheetDocument excelDoc = SpreadsheetDocument.Create(output, DocumentFormat.OpenXml.SpreadsheetDocumentType.Workbook))
        {                 

            WorkbookPart workbookPart1 = excelDoc.AddWorkbookPart();
            WorksheetPart worksheetPart1 = workbookPart1.AddNewPart<WorksheetPart>();
            string sheetId = workbookPart1.GetIdOfPart(worksheetPart1);

            string XML = @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?><workbook xmlns=""http://schemas.openxmlformats.org/spreadsheetml/2006/main"" xmlns:r=""http://schemas.openxmlformats.org/officeDocument/2006/relationships""><sheets><sheet name=""{1}"" sheetId=""1"" r:id=""{0}"" /></sheets></workbook>";
            XML = string.Format(XML, sheetId, "Sheet1");
            using (Stream stream = workbookPart1.GetStream())
            {
                byte[] buffer = (new UTF8Encoding()).GetBytes(XML);
                stream.Write(buffer, 0, buffer.Length);
            }

            XML = @"<?xml version=""1.0"" encoding=""UTF-8"" standalone=""yes""?><worksheet xmlns=""http://schemas.openxmlformats.org/spreadsheetml/2006/main"" >{0}</worksheet>";
            XML = string.Format(XML, strSheetData);
            using (Stream stream = worksheetPart1.GetStream())
            {
                byte[] buffer = (new UTF8Encoding()).GetBytes(XML);
                stream.Write(buffer, 0, buffer.Length);
            }               
            excelDoc.Close();
        }
    }
    return response;
}

这是我在a.xml中的xml数据:

<?xml version="1.0" encoding="utf-8"?>
  <sheetData>
  <row r="1">
  <c r="A1" t="inlineStr">
  <is>
    <t>Table</t>
   </is>
  </c>
  <c r="B1" t="inlineStr">
   <is>
    <t>150</t>
  </is>
    </c>
    <c r="C1" t="inlineStr">
   <is>
    <t>1</t>
   </is>
 </c>
 </row>
  ...
  ...
</sheetData>

0 个答案:

没有答案