使用OpenXML writer写入excel文件时,如何防止将现有值擦除为excel

时间:2019-04-08 09:49:38

标签: c# openxml-sdk

我正在尝试使用OpenXMl writer写入excel文件。我在这里面临的问题是在工作表中写入新值,在工作表中的其他位置擦除以前的值,这是不应该发生的。我只想在相应的列中写,但不应删除其他列中的值。请帮我解决一下这个。 在下面找到代码。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using DocumentFormat.OpenXml.Spreadsheet;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml;
using System.Diagnostics;

namespace OpenXML
{
    class WRITE5
    {
        static void Main(string[] args)
        {
            Stopwatch sw = Stopwatch.StartNew();
            WriteValuesSAX(@"C:\Users\AbdulHameedM\Desktop\1.xlsx", 10);
            sw.Stop();
            Console.WriteLine("Time Taken =" + sw.ElapsedMilliseconds);
            Console.ReadKey();
        }

        static void WriteValuesSAX(string filename, int numRows)
        {
            using (SpreadsheetDocument myDoc = SpreadsheetDocument.Open(filename, true))
            {
                List<OpenXmlAttribute> oxa;

                WorkbookPart workbookPart = myDoc.WorkbookPart;
                WorksheetPart worksheetPart = workbookPart.WorksheetParts.First();

                OpenXmlWriter writer = OpenXmlWriter.Create(worksheetPart);

                writer.WriteStartElement(new Worksheet());
                writer.WriteStartElement(new SheetData());

                for (int i = 1; i <= 500; ++i)
                {
                    oxa = new List<OpenXmlAttribute>();
                    // this is the row index
                    oxa.Add(new OpenXmlAttribute("r", null, i.ToString()));

                    writer.WriteStartElement(new Row(), oxa);


                    oxa = new List<OpenXmlAttribute>();

                    // this is the data type ("t"), with CellValues.String ("str")
                    oxa.Add(new OpenXmlAttribute("t", null, "str"));

                    // it's suggested you also have the cell reference, but
                    // you'll have to calculate the correct cell reference yourself.
                    // Here's an example:
                    oxa.Add(new OpenXmlAttribute("r", null, "A" + i));
                    //oxa.Add(new OpenXmlAttribute("r", null, "A" + i));

                    writer.WriteStartElement(new Cell(), oxa);

                    writer.WriteElement(new CellValue(string.Format("Microsoft")));

                    // this is for Cell
                    writer.WriteEndElement();


                    // this is for Row
                    writer.WriteEndElement();
                }
                writer.Close();
            }
        }
    }
}

0 个答案:

没有答案