Я загрузил файл Excel (xlsx) в библиотеку документов sharepoint, в которой есть некоторые данные, как показано на рисунке ниже:
Теперь,Я хочу вставить еще одну строку с некоторыми данными, используя C #, и хочу сохранить поток файлов, а затем сохранить существующий файл Excel с последними изменениями в библиотеке документов Share point, как показано на рисунке ниже:
Вот код, который я пробовал
public static void Start()
{
MemoryStream ms = new MemoryStream();
ClientContext clientContext = new ClientContext("https://xxxx.com/site/POC/");
SecureString secureString = new SecureString();
foreach (char c in "aksjfqwjfiwjxmAMC")
{
secureString.AppendChar(c);
}
List list = clientContext.Web.Lists.GetByTitle("Documents");
clientContext.Credentials = new SharePointOnlineCredentials("abc@domain.com", secureString);
ListItemCollection col = list.GetItems(new CamlQuery());
clientContext.Load(col);
clientContext.ExecuteQuery();
foreach (var doc in col)
{
Microsoft.SharePoint.Client.File f = doc.File;
clientContext.Load(f);
clientContext.ExecuteQuery();
Console.WriteLine(f.Name);
if (f.Name.Equals("TestingExcel.xlsx"))
{
FileInformation fileInfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(clientContext, (string)f.ServerRelativeUrl);
CopyStream(fileInfo.Stream, ms);
using (SpreadsheetDocument docc = SpreadsheetDocument.Open(ms, true))
{
WorkbookPart workbookPart = docc.WorkbookPart;
Workbook workbook = docc.WorkbookPart.Workbook;
//Read the first Sheet from Excel file.
var sheetNames = docc.WorkbookPart.Workbook.Sheets.ChildElements;
Worksheet worksheet;
int sheetIndex = 0;
Dictionary<string, string> response = new Dictionary<string, string>();
foreach (WorksheetPart worksheetpart in workbook.WorkbookPart.WorksheetParts)
{
worksheet = worksheetpart.Worksheet;
// Grab the sheet name each time through your loop
string sheetName = workbookPart.Workbook.Descendants<Sheet>().ElementAt(sheetIndex).Name;
if (sheetName == "Sheet1")
{
List<string> resp = new List<string>();
Sheet sheet = sheetNames[sheetIndex] as Sheet;
Worksheet reqdsheet = (docc.WorkbookPart.GetPartById(sheet.Id.Value) as WorksheetPart).Worksheet;
//Fetch all the rows present in the Worksheet.
IEnumerable<Row> rows = reqdsheet.GetFirstChild<SheetData>().Descendants<Row>();
uint rowCount = Convert.ToUInt16(rows.Count());
List<string> cellref = new List<string>();
cellref.Add("A");
Cell cel = InsertCellInWorksheet("A", rowCount + 1, worksheet);
cel.DataType = new EnumValue<CellValues>(CellValues.SharedString);
worksheetpart.Worksheet.Save();
workbookPart.Workbook.Save();
SP.File.SaveBinaryDirect(clientContext, f.ServerRelativeUrl, ms,true);
docc.Close();
}
}
}
}
private static Cell InsertCellInWorksheet(string columnName, uint rowIndex, Worksheet worksheet)
{
// Worksheet worksheet1 = worksheet.Worksheet;
SheetData sheetData = worksheet.GetFirstChild<SheetData>();
string cellReference = columnName + rowIndex;
// If the worksheet does not contain a row with the specified row index, insert one.
Row row;
if (sheetData.Elements<Row>().Where(r => r.RowIndex == rowIndex).Count() != 0)
{
row = sheetData.Elements<Row>().Where(r => r.RowIndex == rowIndex).First();
}
else
{
row = new Row() { RowIndex = rowIndex };
sheetData.Append(row);
}
// If there is not a cell with the specified column name, insert one.
if (row.Elements<Cell>().Where(c => c.CellReference.Value == columnName + rowIndex).Count() > 0)
{
return row.Elements<Cell>().Where(c => c.CellReference.Value == cellReference).First();
}
else
{
// Cells must be in sequential order according to CellReference. Determine where to insert the new cell.
Cell refCell = null;
foreach (Cell cell1 in row.Elements<Cell>())
{
if (string.Compare(cell1.CellReference.Value, cellReference, true) > 0)
{
refCell = cell1;
break;
}
}
Cell newCell1 = new Cell() { CellReference = cellReference };
row.InsertBefore(newCell1, refCell);
// Set the cell value to be a numeric value of 100.
newCell1.CellValue = new CellValue("Teddy");
newCell1.DataType = new EnumValue<CellValues>(CellValues.Number);
worksheet.Save();
//return newCell;
return newCell1;
}
}
И когда я открываю Excel в sharepoint, я получаю сообщение об ошибке, показанное на приведенном ниже снимке экрана