C# 使用OpenXml将文本写入特定Excel单元格时出现问题

C# 使用OpenXml将文本写入特定Excel单元格时出现问题,c#,excel,openxml,vba,C#,Excel,Openxml,Vba,我想要实现的目标如下所示: public static void Main(string[] args) { WriteExcelService writeExcelService = new WriteExcelService(); Dictionary<string, List<string>> contentList = new Dictionary<string, List<string>> { {

我想要实现的目标如下所示:

public static void Main(string[] args)
{
    WriteExcelService writeExcelService = new WriteExcelService();
    Dictionary<string, List<string>> contentList = new Dictionary<string, List<string>>
    {
        { "en-US",new List<string> (new string[] { "Dummy text 01","Dummy text 02"}) },
        { "es-ES",new List<string> (new string[] { "Texto ficticio 01", "Texto ficticio 02"}) }
    };
    string inputFile = @"C:\{username}\Desktop\Valentines_Day.xlsx";
    string sheetName = "Copy";

    writeExcelService.WriteValueToCell(inputFile, sheetName, contentList);
}
char columnName = 'I';
        uint rowNumber = 1;
        foreach (var keys in contentList.Keys)
        {
            foreach (var value in contentList.Where(v => v.Key == keys).SelectMany(v => v.Value))
            {
                string cellAddress = String.Concat(columnName, rowNumber);
                this.Write(filepath, sheetName, value, cellAddress, rowNumber);
                int tempColumn = (int)columnName;
                columnName = (char)++tempColumn;
            }
            columnName = 'I';
            ++rowNumber;
        }
private void Write(string filepath, string sheetName, string value, string cellAddress,uint rowNumber)
{
    // Create a spreadsheet document by supplying the filepath.
    // By default, AutoSave = true, Editable = true, and Type = xlsx.
    using (SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Create(filepath, SpreadsheetDocumentType.Workbook))
    {
        //writeExcelService.WriteValueToCell(outputFilePath, sheetName, cellAddress, value.Value);
        // 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 = sheetName };
        sheets.Append(sheet);

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

        // Add a row to the cell table.
        Row row;
        row = new Row() { RowIndex = rowNumber };
        sheetData.Append(row);

        // In the new row, find the column location to insert a cell.
        Cell refCell = null;
        foreach (Cell cell in row.Elements<Cell>())
        {
            if (string.Compare(cell.CellReference.Value, cellAddress, true) > 0)
            {
                refCell = cell;
                break;
            }
        }

        // Add the cell to the cell table.
        Cell newCell = new Cell() { CellReference = cellAddress };
        row.InsertBefore(newCell, refCell);

        // Set the cell value to be a numeric value.
        newCell.CellValue = new CellValue(value);
        newCell.DataType = new EnumValue<CellValues>(CellValues.Number);
    }
}

我得到的结果和问题如下所示:

public static void Main(string[] args)
{
    WriteExcelService writeExcelService = new WriteExcelService();
    Dictionary<string, List<string>> contentList = new Dictionary<string, List<string>>
    {
        { "en-US",new List<string> (new string[] { "Dummy text 01","Dummy text 02"}) },
        { "es-ES",new List<string> (new string[] { "Texto ficticio 01", "Texto ficticio 02"}) }
    };
    string inputFile = @"C:\{username}\Desktop\Valentines_Day.xlsx";
    string sheetName = "Copy";

    writeExcelService.WriteValueToCell(inputFile, sheetName, contentList);
}
char columnName = 'I';
        uint rowNumber = 1;
        foreach (var keys in contentList.Keys)
        {
            foreach (var value in contentList.Where(v => v.Key == keys).SelectMany(v => v.Value))
            {
                string cellAddress = String.Concat(columnName, rowNumber);
                this.Write(filepath, sheetName, value, cellAddress, rowNumber);
                int tempColumn = (int)columnName;
                columnName = (char)++tempColumn;
            }
            columnName = 'I';
            ++rowNumber;
        }
private void Write(string filepath, string sheetName, string value, string cellAddress,uint rowNumber)
{
    // Create a spreadsheet document by supplying the filepath.
    // By default, AutoSave = true, Editable = true, and Type = xlsx.
    using (SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Create(filepath, SpreadsheetDocumentType.Workbook))
    {
        //writeExcelService.WriteValueToCell(outputFilePath, sheetName, cellAddress, value.Value);
        // 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 = sheetName };
        sheets.Append(sheet);

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

        // Add a row to the cell table.
        Row row;
        row = new Row() { RowIndex = rowNumber };
        sheetData.Append(row);

        // In the new row, find the column location to insert a cell.
        Cell refCell = null;
        foreach (Cell cell in row.Elements<Cell>())
        {
            if (string.Compare(cell.CellReference.Value, cellAddress, true) > 0)
            {
                refCell = cell;
                break;
            }
        }

        // Add the cell to the cell table.
        Cell newCell = new Cell() { CellReference = cellAddress };
        row.InsertBefore(newCell, refCell);

        // Set the cell value to be a numeric value.
        newCell.CellValue = new CellValue(value);
        newCell.DataType = new EnumValue<CellValues>(CellValues.Number);
    }
}
这是我的代码生成的结果文件,应该有预期的内容

单击“是”按钮后的窗口提示

我的运行代码如下所示:

主要方法:

public static void Main(string[] args)
{
    WriteExcelService writeExcelService = new WriteExcelService();
    Dictionary<string, List<string>> contentList = new Dictionary<string, List<string>>
    {
        { "en-US",new List<string> (new string[] { "Dummy text 01","Dummy text 02"}) },
        { "es-ES",new List<string> (new string[] { "Texto ficticio 01", "Texto ficticio 02"}) }
    };
    string inputFile = @"C:\{username}\Desktop\Valentines_Day.xlsx";
    string sheetName = "Copy";

    writeExcelService.WriteValueToCell(inputFile, sheetName, contentList);
}
char columnName = 'I';
        uint rowNumber = 1;
        foreach (var keys in contentList.Keys)
        {
            foreach (var value in contentList.Where(v => v.Key == keys).SelectMany(v => v.Value))
            {
                string cellAddress = String.Concat(columnName, rowNumber);
                this.Write(filepath, sheetName, value, cellAddress, rowNumber);
                int tempColumn = (int)columnName;
                columnName = (char)++tempColumn;
            }
            columnName = 'I';
            ++rowNumber;
        }
private void Write(string filepath, string sheetName, string value, string cellAddress,uint rowNumber)
{
    // Create a spreadsheet document by supplying the filepath.
    // By default, AutoSave = true, Editable = true, and Type = xlsx.
    using (SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Create(filepath, SpreadsheetDocumentType.Workbook))
    {
        //writeExcelService.WriteValueToCell(outputFilePath, sheetName, cellAddress, value.Value);
        // 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 = sheetName };
        sheets.Append(sheet);

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

        // Add a row to the cell table.
        Row row;
        row = new Row() { RowIndex = rowNumber };
        sheetData.Append(row);

        // In the new row, find the column location to insert a cell.
        Cell refCell = null;
        foreach (Cell cell in row.Elements<Cell>())
        {
            if (string.Compare(cell.CellReference.Value, cellAddress, true) > 0)
            {
                refCell = cell;
                break;
            }
        }

        // Add the cell to the cell table.
        Cell newCell = new Cell() { CellReference = cellAddress };
        row.InsertBefore(newCell, refCell);

        // Set the cell value to be a numeric value.
        newCell.CellValue = new CellValue(value);
        newCell.DataType = new EnumValue<CellValues>(CellValues.Number);
    }
}
写入方法:

public static void Main(string[] args)
{
    WriteExcelService writeExcelService = new WriteExcelService();
    Dictionary<string, List<string>> contentList = new Dictionary<string, List<string>>
    {
        { "en-US",new List<string> (new string[] { "Dummy text 01","Dummy text 02"}) },
        { "es-ES",new List<string> (new string[] { "Texto ficticio 01", "Texto ficticio 02"}) }
    };
    string inputFile = @"C:\{username}\Desktop\Valentines_Day.xlsx";
    string sheetName = "Copy";

    writeExcelService.WriteValueToCell(inputFile, sheetName, contentList);
}
char columnName = 'I';
        uint rowNumber = 1;
        foreach (var keys in contentList.Keys)
        {
            foreach (var value in contentList.Where(v => v.Key == keys).SelectMany(v => v.Value))
            {
                string cellAddress = String.Concat(columnName, rowNumber);
                this.Write(filepath, sheetName, value, cellAddress, rowNumber);
                int tempColumn = (int)columnName;
                columnName = (char)++tempColumn;
            }
            columnName = 'I';
            ++rowNumber;
        }
private void Write(string filepath, string sheetName, string value, string cellAddress,uint rowNumber)
{
    // Create a spreadsheet document by supplying the filepath.
    // By default, AutoSave = true, Editable = true, and Type = xlsx.
    using (SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Create(filepath, SpreadsheetDocumentType.Workbook))
    {
        //writeExcelService.WriteValueToCell(outputFilePath, sheetName, cellAddress, value.Value);
        // 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 = sheetName };
        sheets.Append(sheet);

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

        // Add a row to the cell table.
        Row row;
        row = new Row() { RowIndex = rowNumber };
        sheetData.Append(row);

        // In the new row, find the column location to insert a cell.
        Cell refCell = null;
        foreach (Cell cell in row.Elements<Cell>())
        {
            if (string.Compare(cell.CellReference.Value, cellAddress, true) > 0)
            {
                refCell = cell;
                break;
            }
        }

        // Add the cell to the cell table.
        Cell newCell = new Cell() { CellReference = cellAddress };
        row.InsertBefore(newCell, refCell);

        // Set the cell value to be a numeric value.
        newCell.CellValue = new CellValue(value);
        newCell.DataType = new EnumValue<CellValues>(CellValues.Number);
    }
}
但我有个例外

此父级只允许该类型的一个实例

有人能帮我吗


请提前欣赏。

excel中的字符串保存在sharedStringTable下。插入字符串时,添加字符串或引用sharedStringTable中的字符串非常重要。此外,还需要为单元格提供正确的
数据类型。在代码中,将所有值作为数字插入:

// Set the cell value to be a numeric value.
newCell.CellValue = new CellValue(value);
newCell.DataType = new EnumValue<CellValues>(CellValues.Number);
//将单元格值设置为数值。
newCell.CellValue=新的CellValue(值);
newCell.DataType=新的枚举值(CellValues.Number);
要插入字符串,我建议在创建新单元格后使用以下方法:

private SpreadsheetDocument _spreadSheet;
private WorksheetPart _worksheetPart;
..
..
private void UpdateCell(Cell cell, DataTypes type, string text)
{
    if (type == DataTypes.String)
    {
        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());
                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());
    }
    else if (type == DataTypes.Number)
    {
        cell.CellValue = new CellValue(text);
        cell.DataType = CellValues.Number;
    }
    else if (type == DataTypes.DateTime)
    {

        cell.DataType = CellValues.Number;
        cell.StyleIndex = Convert.ToUInt32(_dateStyleIndex);

        DateTime dateTime = DateTime.Parse(text);
        double oaValue = dateTime.ToOADate();
        cell.CellValue = new CellValue(oaValue.ToString(CultureInfo.InvariantCulture));
    }
    _worksheetPart.Worksheet.Save();
}
private SpreadsheetDocument\u电子表格;
私人工作表部分(u工作表部分);;
..
..
私有void UpdateCell(单元格、数据类型、字符串文本)
{
if(type==DataTypes.String)
{
cell.DataType=CellValues.SharedString;
if(!\u电子表格.WorkbookPart.GetPartsOfType().Any())
{
_电子表格.WorkbookPart.AddNewPart();
}
var sharedStringTablePart=_电子表格.WorkbookPart.GetPartSoftType().First();
if(sharedStringTablePart.SharedStringTable==null)
{
sharedStringTablePart.SharedStringTable=新的SharedStringTable();
}
//遍历共享字符串表以检查该值是否已存在。
foreach(sharedStringTablePart.SharedStringTable.Elements()中的SharedStringItem ssItem)
{
如果(ssItem.InnerText==文本)
{
cell.CellValue=新的CellValue(ssItem.ElementsBefore().Count().ToString());
返回;
}
}
//该部分中不存在文本。请创建SharedStringItem。
var item=sharedStringTablePart.SharedStringTable.AppendChild(新SharedStringItem(新文本));
cell.CellValue=新的CellValue(item.ElementsBefore().Count().ToString());
}
else if(type==DataTypes.Number)
{
cell.CellValue=新的CellValue(文本);
cell.DataType=CellValues.Number;
}
else if(type==DataTypes.DateTime)
{
cell.DataType=CellValues.Number;
cell.StyleIndex=Convert.ToUInt32(_dateStyleIndex);
DateTime DateTime=DateTime.Parse(文本);
double oaValue=dateTime.ToOADate();
cell.CellValue=新的CellValue(oaValue.ToString(CultureInfo.InvariantCulture));
}
_worksheetPart.Worksheet.Save();
}

我自己已经想出了解决办法。我已经传递了字符串内容列表,并将它们全部写入相应的单元格,然后关闭了
电子表格文档
。这样就可以一次创建
电子表格文档
。工作代码如下:

public void WriteValueToCell(string filepath, string sheetName, Dictionary<string, List<string>> contentList)
{
    // Create a spreadsheet document by supplying the filepath.
    // By default, AutoSave = true, Editable = true, and Type = xlsx.
    using (SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Create(filepath, SpreadsheetDocumentType.Workbook, true))
    {
        // Add a WorkbookPart to the document.
        WorkbookPart workbookpart = spreadsheetDocument.AddWorkbookPart();
        workbookpart.Workbook = new Workbook();

        //Add a WorkbookStylesPart to the workbookpart
        WorkbookStylesPart stylesPart = workbookpart.AddNewPart<WorkbookStylesPart>();
        stylesPart.Stylesheet = new Stylesheet();

        // 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 = sheetName };
        sheets.Append(sheet);

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

        char columnName = 'I';
        uint rowNumber = 1;
        foreach (var keys in contentList.Keys)
        {
            foreach (var value in contentList.Where(v => v.Key == keys).SelectMany(v => v.Value))
            {
                string cellAddress = String.Concat(columnName, rowNumber);
                // Add a row to the cell table.
                Row row;
                row = new Row() { RowIndex = rowNumber };
                sheetData.Append(row);

                // In the new row, find the column location to insert a cell.
                Cell refCell = null;
                foreach (Cell cell in row.Elements<Cell>())
                {
                    if (string.Compare(cell.CellReference.Value, cellAddress, true) > 0)
                    {
                        refCell = cell;
                        break;
                    }
                }

                // Add the cell to the cell table.
                Cell newCell = new Cell() { CellReference = cellAddress };
                row.InsertBefore(newCell, refCell);
                // Set the cell value to be a numeric value.
                newCell.CellValue = new CellValue(value);
                newCell.DataType = new EnumValue<CellValues>(CellValues.String);

                int tempColumn = (int)columnName;
                columnName = (char)++tempColumn;
            }
            columnName = 'I';
            ++rowNumber;
        }
    }
}
public void WriteValueToCell(字符串文件路径、字符串表名、字典内容列表)
{
//通过提供文件路径创建电子表格文档。
//默认情况下,AutoSave=true、Editable=true和Type=xlsx。
使用(SpreadsheetDocument SpreadsheetDocument=SpreadsheetDocument.Create(文件路径,SpreadsheetDocumentType.工作簿,true))
{
//将工作簿部件添加到文档中。
WorkbookPart WorkbookPart=电子表格文档.AddWorkbookPart();
workbookpart.工作簿=新工作簿();
//将WorkbookStylesPart添加到workbookpart
WorkbookStylesPart-stylesPart=workbookpart.AddNewPart();
stylesPart.Stylesheet=新样式表();
//将工作表部件添加到工作簿部件。
WorksheetPart WorksheetPart=workbookpart.AddNewPart();
worksheetPart.Worksheet=新工作表(new SheetData());
//将工作表添加到工作簿中。
Sheets Sheets=spreadsheetDocument.WorkbookPart.Workbook.AppendChild(新工作表());
//附加新工作表并将其与工作簿关联。
Sheet Sheet=new Sheet(){Id=spreadsheetDocument.WorkbookPart.GetIdOfPart(worksheetPart),SheetId=1,Name=sheetName};
附页(页);
//获取sheetData单元格表。
SheetData SheetData=worksheetPart.Worksheet.GetFirstChild();
char columnName='I';
uint rowNumber=1;
foreach(contentList.keys中的var键)
{
foreach(contentList.Where中的var值(v=>v.Key==keys)。SelectMany(v=>v.value))
{
string cellAddress=string.Concat(columnName,rowNumber);
//向单元格表中添加一行。
行行;
行=新行(){RowIndex=rowNumber};
sheetData.Append(行);
//在新行中,找到要插入单元格的列位置。
Cell refCell=null;
foreach(row.Elements()中的单元格)
{
if(string.Compare(cell.CellReference.Value,cellAddress,true)>0)
{
refCell=单元格;
打破
}
}
//将单元格添加到单元格表中。
Cell newCell=newCell(){CellReference=cellAddress};
row.InsertBefore(newCell、refCell);
//将单元格值设置为数值。
newCell.CellValue=新的CellValue(值);
newCell.DataType=新的枚举值(CellValues.String);
int tempColumn=(int)columnNam