OpenXML创建的SpreadSheet发现不可读的内容

时间:2019-03-18 02:51:40

标签: c# openxml

我正在使用如下OpenXML文件创建Excel文件

 class Program
{
    static void Main(string[] args)
    {
        Dictionary<string, string> dic1 = new Dictionary<string, string>
        {
            {"H1","FPT1" },
            {"AA1","IPN1" },
        };

        Dictionary<string, string> dic2 = new Dictionary<string, string>
        {
            {"H2","FPT2" },
            {"AA2","IPN2" },
        };
        Dictionary<string, string> dic3 = new Dictionary<string, string>
        {
            {"H3","FPT3" },
            {"AA3","IPN3" },
        };
        Dictionary<string, string> dic4 = new Dictionary<string, string>
        {
            {"H4","FPT4" },
            {"AA4","IPN4" },
        };
        List<Dictionary<string, string>> data = new List<Dictionary<string, string>>();
        data.Add(dic1);
        data.Add(dic2);
        data.Add(dic3);
        data.Add(dic4);

        CreateSpreadsheetWorkbook(@"J:\OpenXMLApp\Myfile.xlsx", data);
    }

    public static void CreateSpreadsheetWorkbook(string filepath, List<Dictionary<string, string>> Data)
    {
        // Create a spreadsheet document by supplying the filepath.
        // By default, AutoSave = true, Editable = true, and Type = xlsx.
        SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Create(filepath, SpreadsheetDocumentType.Workbook);

        // Add a WorkbookPart to the document.
        WorkbookPart workbookpart = spreadsheetDocument.AddWorkbookPart();
        workbookpart.Workbook = new Workbook();

        // Add a WorksheetPart to the WorkbookPart.
        WorksheetPart worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
        worksheetPart.Worksheet = new Worksheet(new SheetData());

        // Add Sheets to the Workbook.
        Sheets sheets = spreadsheetDocument.WorkbookPart.Workbook.AppendChild<Sheets>(new Sheets());

        // Append a new worksheet and associate it with the workbook.
        Sheet sheet = new Sheet() { Id = spreadsheetDocument.WorkbookPart.GetIdOfPart(worksheetPart), SheetId = 1, Name = "mySheet" };
        sheets.Append(sheet);

        // Get the sheetData cell table.
        SheetData sheetData = worksheetPart.Worksheet.GetFirstChild<SheetData>();

        int rowindex = 2;
        foreach (Dictionary<string, string> _row in Data)
        {
            Row row = new Row
            {
                RowIndex = (uint)rowindex
            };
            sheetData.Append(row);
            foreach (KeyValuePair<string, string> pair in _row)
            {
                string CellAddressForCurrentAttribute = string.Empty;

                Cell refcell = row.Elements<Cell>().Where(c => string.Compare(c.CellReference.Value, CellAddressForCurrentAttribute, true) == 0).FirstOrDefault();
                Cell newCell = new Cell { CellReference = pair.Key };
                newCell.InlineString = new InlineString() { Text = new Text(pair.Value) };
                newCell.DataType = CellValues.SharedString;
                row.InsertBefore(newCell, refcell);
            }
        }
        rowindex++;
        spreadsheetDocument.Save();
        // Close the document.
        spreadsheetDocument.Close();
    }
}

现在,当我打开由上述代码创建的Excel文件时,出现以下错误。 Excel Error

在日志文件中,我得到如下信息

    <?xml version="1.0" encoding="UTF-8"?>
<recoveryLog xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
   <logFileName>error199640_01.xml</logFileName>
   <summary>Errors were detected in file 'J:\OpenXMLApp\Myfile.xlsx'</summary>
   <removedRecords>
      <removedRecord>Removed Records: Cell information from /xl/worksheets/sheet1.xml part</removedRecord>
   </removedRecords>
   <repairedRecords>
      <repairedRecord>Repaired Records: Cell information from /xl/worksheets/sheet1.xml part</repairedRecord>
   </repairedRecords>
</recoveryLog>

OpenXML在生成Excel文件时出现什么问题?我正在使用MSDN网站here上的示例代码段.................................... ............

1 个答案:

答案 0 :(得分:0)

OpenXML就像一个固执的女朋友。它需要以特定的方式完成操作,如果您更改了哪怕一丁点的操作,它都会崩溃。

请在下面找到经过修改的代码,该代码有望按您希望的方式工作。我已经对其进行了测试,并且它产生的输出没有给出任何错误。

class Program
    {
        static void Main(string[] args)
        {
            var dic1 = new Dictionary<string, string>
        {
            {"H2","FPT1" },
            {"AA2","IPN1" },
        };

            var dic2 = new Dictionary<string, string>
        {
            {"H3","FPT2" },
            {"AA3","IPN2" },
        };
            var dic3 = new Dictionary<string, string>
        {
            {"H4","FPT3" },
            {"AA4","IPN3" },
        };
            var dic4 = new Dictionary<string, string>
        {
            {"H5","FPT4" },
            {"AA5","IPN4" },
        };
            var data = new List<Dictionary<string, string>>
            {
                dic1,
                dic2,
                dic3,
                dic4
            };

            CreateSpreadsheetWorkbook(@"J:\OpenXMLApp\Myfile.xlsx", data);
        }

        public static void CreateSpreadsheetWorkbook(string filepath, List<Dictionary<string, string>> Data)
        {
            // Create a spreadsheet document by supplying the filepath.
            // By default, AutoSave = true, Editable = true, and Type = xlsx.
            var spreadsheetDocument = SpreadsheetDocument.Create(filepath, SpreadsheetDocumentType.Workbook);

            // Add a WorkbookPart to the document.
            var workbookpart = spreadsheetDocument.AddWorkbookPart();
            workbookpart.Workbook = new Workbook();

            // Add Sheets to the Workbook.
            var sheets = spreadsheetDocument.WorkbookPart.Workbook.AppendChild(new Sheets());

            // Add a WorksheetPart to the WorkbookPart.
            var worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
            // Get the sheetData cell table.
            var sheetData = new SheetData();
            worksheetPart.Worksheet = new Worksheet();

            var rowindex = 2;
            foreach (var _row in Data)
            {
                var row = new Row
                {
                    RowIndex = (uint)rowindex
                };
                foreach (var pair in _row)
                {
                    var newCell = new Cell { CellReference = pair.Key, DataType = CellValues.InlineString };
                    var inlineString = new InlineString();
                    var t = new Text
                    {
                        Text = pair.Value
                    };
                    inlineString.AppendChild(t);
                    newCell.AppendChild(inlineString);
                    row.AppendChild(newCell);
                }
                sheetData.AppendChild(row);
                rowindex++;
            }

            worksheetPart.Worksheet.Append(sheetData);

            // Append a new worksheet and associate it with the workbook.
            var sheet = new Sheet() { Id = spreadsheetDocument.WorkbookPart.GetIdOfPart(worksheetPart), SheetId = 1, Name = "mySheet" };
            sheets.Append(sheet);

            spreadsheetDocument.Save();
            // Close the document.
            spreadsheetDocument.Close();
        }
    }