OpenXML создал SpreadSheet обнаружил нечитаемый контент - PullRequest
0 голосов
/ 18 марта 2019

Я создаю файл Excel с файлом OpenXML следующим образом

 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 здесь .................................. ..............

1 Ответ

0 голосов
/ 18 марта 2019

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();
        }
    }
...