#c# #excel #openxml
#c# #excel #openxml
Вопрос:
Я пытаюсь получить данные из базы данных sql в шаблон Excel, у меня есть захват шаблона Excel в потоке, где я пытаюсь манипулировать данными Excel на основе выходных данных sql, ниже приведен код для справки.
foreach (DataRow item in data.Rows)
{
foreach (var row in rows)
{
if (reportname == "PivotTable")
{
int i = 0;
var cells = row.Elements<Cell>();
foreach (var cell in cells)
{
string col = tem.ItemArray[i].ToString();
cell.CellValue = new CellValue(col);
string cellRef = cell.CellReference.InnerText;
cell.DataType = new EnumValue<CellValues>(CellValues.Number);
i ;
}
worksheetPart.Worksheet.Save();
}
}
spreadSheetDocument.WorkbookPart.Workbook.CalculationProperties.ForceFullCalculation = true;
spreadSheetDocument.WorkbookPart.Workbook.CalculationProperties.FullCalculationOnLoad = true;
workbookPart.Workbook.Save();
}
Ответ №1:
Используйте DocumentFormat.OpenXML
using (var memoryStream = new MemoryStream())
{
using (var excel = SpreadsheetDocument.Create(memoryStream, DocumentFormat.OpenXml.SpreadsheetDocumentType.Workbook, true))
{
workbookPart = excel.AddWorkbookPart();
workbookPart.Workbook = new Workbook();
uint sheetId = 1;
excel.WorkbookPart.Workbook.Sheets = new Sheets();
Sheets sheets = excel.WorkbookPart.Workbook.GetFirstChild<Sheets>();
Worksheet worksheet = new Worksheet();
wSheetPart.Worksheet = worksheet;
SheetData sheetData = new SheetData();
worksheet.Append(sheetData);
int i=1;
string[] strColumnArray =
{"A","B","C","D","E","F","G","H","I","J","K","L"};
foreach (DataRow item in data.Rows)
{
foreach (var row in rows)
{
if (reportname == "PivotTable")
{
int j = 1;
var cells = row.Elements<Cell>();
foreach (var cell in cells)
{
string col = tem.ItemArray[i].ToString();
AddToCell(sheetData, i, j, strColumnArray[j-1] , CellValues.Number, col);
j ;
}
}
i ;
}
}
excel.Close();
}
FileStream fileStream = new FileStream(AppDomain.CurrentDomain.BaseDirectory "DBToExcel.xlsx", FileMode.Create, FileAccess.Write);
memoryStream.WriteTo(fileStream);
fileStream.Close();
memoryStream.Close();
}
Создайте метод для добавления в ячейку:
public void AddToCell(SheetData sheetData, UInt32Value styleIndex, UInt32 uint32rowIndex, string strColumnName, DocumentFormat.OpenXml.EnumValue<CellValues> CellDataType, string strCellValue)
{
Row row = new Row() { RowIndex = uint32rowIndex };
Cell cell = new Cell();
cell = new Cell() { StyleIndex = styleIndex };
cell.CellReference = strColumnName row.RowIndex.ToString();
cell.DataType = CellDataType;
cell.CellValue = new CellValue(strCellValue);
row.AppendChild(cell);
sheetData.Append(row);
}