修复的记录:创建的工作表中的单元信息

时间:2017-06-11 07:54:36

标签: java c# excel openxml

打开OpenXML创建的电子表格时收到错误。错误如下。

  

修复记录:xl / worksheets / sheet.xml部分单元格信息

private void SavexlsExcelFile(String fullPathName)
    {
        using (SpreadsheetDocument document = SpreadsheetDocument.Create(fullPathName, SpreadsheetDocumentType.Workbook))
        {

            WorkbookPart workbookPart = document.AddWorkbookPart();
            workbookPart.Workbook = new Workbook();

            worksheetPart = workbookPart.AddNewPart<WorksheetPart>();
            worksheetPart.Worksheet = new Worksheet();

            Columns columns = new Columns();

            worksheetPart.Worksheet.AppendChild(columns);

            Sheets sheets = workbookPart.Workbook.AppendChild(new Sheets());

            Sheet sheet = new Sheet() { Id = workbookPart.GetIdOfPart(worksheetPart), SheetId = 1, Name = "Sheet" };
            sheets.Append(sheet);

            workbookPart.Workbook.Save();

            sheetData = worksheetPart.Worksheet.AppendChild(new SheetData());


            List<List<string>> dataRow = new List<List<string>>();
            List<String> dtRow = new List<String>();

            Row row = new Row();

            for (int i = 0; i < dataGridView1.RowCount; i++)
            {
                for (int j = 0; j < dataGridView1.ColumnCount; j++)
                {
                    if (i == 0)
                    {
                        Cell dataCell = new Cell();
                        dataCell.DataType = CellValues.String;
                        CellValue cellValue = new CellValue();

                        cellValue.Text = dataGridView1.Columns[j].Name;
                        dataCell.StyleIndex = 2;
                        dataCell.Append(cellValue);
                        row.AppendChild(dataCell);
                        //dataColumn.Add(dataGridView1.Columns[j].Name);
                    }
                    dtRow.Add(dataGridView1.Rows[i].Cells[j].Value.ToString());
                }
            }

            dataRow.Add(dtRow);
            sheetData.AppendChild(row);

            row = new Row();

            foreach (List<string> datarow in dataRow)
            {
                row = new Row();
                foreach(string dtrow in datarow)
                {
                    row.Append(ConstructCell(dtrow, CellValues.String, 2));
                }
                sheetData.AppendChild(row);
            }
            worksheetPart.Worksheet.Save();
        }
    }
    private Cell ConstructCell(string value, CellValues dataType, uint styleIndex = 0)
    {
        return new Cell()
        {
            CellValue = new CellValue(value),
            DataType = new EnumValue<CellValues>(dataType),
            StyleIndex = styleIndex
        };
    }

2 个答案:

答案 0 :(得分:0)

Excel中的所有文本都存储在共享字符串表下。您需要在共享字符串表中插入字符串:

string text = dataGridView1.Columns[j].Name; 
cell.DataType = CellValues.SharedString;

if (!_spreadSheet.WorkbookPart.GetPartsOfType<SharedStringTablePart>().Any())
{
    _spreadSheet.WorkbookPart.AddNewPart<SharedStringTablePart>();
}

var sharedStringTablePart = _spreadSheet.WorkbookPart.GetPartsOfType<SharedStringTablePart>().First();
if (sharedStringTablePart.SharedStringTable == null)
{
    sharedStringTablePart.SharedStringTable = new SharedStringTable();
}
//Iterate through shared string table to check if the value is already present.
foreach (SharedStringItem ssItem in sharedStringTablePart.SharedStringTable.Elements<SharedStringItem>())
{
    if (ssItem.InnerText == text)
    {
        cell.CellValue = new CellValue(ssItem.ElementsBefore().Count().ToString());
        SaveChanges();
        return;
    }
}
// The text does not exist in the part. Create the SharedStringItem.
var item = sharedStringTablePart.SharedStringTable.AppendChild(new SharedStringItem(new Text(text)));
cell.CellValue = new CellValue(item.ElementsBefore().Count().ToString());

答案 1 :(得分:0)

There are 2 issues here that I can see. The first is that your use of Columns is incorrect. You should use Columns if you wish to control things such as the width of a column. To use Columns correctly, you'll need to add child Column elements. For example (taken from here):

Columns columns = new Columns();

columns.Append(new Column() { Min = 1, Max = 3, Width = 20, CustomWidth = true });
columns.Append(new Column() { Min = 4, Max = 4, Width = 30, CustomWidth = true });

In your sample you could just remove the following two lines

Columns columns = new Columns();
worksheetPart.Worksheet.AppendChild(columns);

The second issue is the StyleIndex you are using; the style doesn't exist in your document because you haven't added it. The easiest thing to do here is to just remove the StyleIndex altogether.

When debugging files like this, it's always worth looking at the OpenXml Productivity Tool. You can open a generated file in the tool and validate it to see what errors you have in your file.