我可以运行以下代码而不会出现错误或异常(代码方面)
private ExcelRow CreateContentRow(int index, StockHolder stockholder)
{
ExcelRow r = new ExcelRow();
r.RowIndex = (UInt32)index + 1;
int i = 0;
string[] headerColumns = new string[] { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K" };
var eraseThis = stockholder.GetType().GetProperties().Count();
foreach (var prop in stockholder.GetType().GetProperties())
{
ExcelCell c = new ExcelCell();
c.CellReference = headerColumns[i].ToString() + index;
if (prop.PropertyType.ToString().Equals("System.string", StringComparison.InvariantCultureIgnoreCase))
{
var result = prop.GetValue(stockholder, null);
if (result == null)
{
result = "";
}
c.DataType = CellValues.String;
InlineString inlineString = new InlineString();
Text t = new Text();
t.Text = result.ToString();
inlineString.AppendChild(t);
c.AppendChild(inlineString);
}
//Other "if" statements here for checking bool and numeric (similar to the above "if" statement, but none of them are used at this time
return r;
}
"索引"参数是我试图添加到的工作表中的行数(它似乎能够读取工作表名称(因为只有一个)但是" Stockholder" parameter是带有填充数据的自定义对象(都不是null)
问题是我之后尝试打开Excel文档
当我单击是时,它会显示此弹出窗口
当我尝试搜索时,结果对于另一个第三方库(以" ERPPS"或类似的东西开头)更有用。在调试时,属性似乎正确映射(使用另一种方法进行映射,并且它们仍然是所有字符串)。任何帮助或链接将不胜感激,因为我已经有一段时间了解这一点。并且,目前使用网络应用程序或表单不是替代方案(很久以前会感到羞耻)。感谢
编辑 - 此外,这里是调用方法(因为它也可能是它的一部分)
private void InsertIntoExistingExcel(StockHolder sh)
{
using (SpreadsheetDocument myWorkbook = SpreadsheetDocument.Open(locationOfExcelFile, true))
{
WorkbookPart workbookPart = myWorkbook.WorkbookPart;
var stockHolderInfo_Sheet = myWorkbook.WorkbookPart.Workbook.Sheets.GetFirstChild<Sheet>();
IEnumerable<Sheet> Sheets = new List<Sheet>() { stockHolderInfo_Sheet };
if (Sheets.Count() > 0)
{
string relationshipId = Sheets.First().Id.Value;
WorksheetPart worksheetPart = (WorksheetPart)myWorkbook.WorkbookPart.GetPartById(relationshipId);
SheetData sheetdata = worksheetPart.Worksheet.GetFirstChild<SheetData>();
var sheetDataCount = sheetdata.Count();
var newContentRow = CreateContentRow(sheetDataCount, sh);
sheetdata.AppendChild(newContentRow);
workbookPart.Workbook.Save();
}
}
}
答案 0 :(得分:0)
解决了!或者更确切地说,使用不同的方法
private void interopExcelInsertion(StockHolder sh, int rowNumberToUpdate)
{
ExcelInterop.Application oApp;
ExcelInterop.Worksheet oSheet;
ExcelInterop.Workbook oBook;
oApp = new ExcelInterop.Application();
oBook = oApp.Workbooks.Open(locationAndNameOfExcelFile);
oSheet = oBook.Worksheets[1] as Microsoft.Office.Interop.Excel.Worksheet;
var rowToUpdate = rowNumberToUpdate > 0 ? rowNumberToUpdate : oSheet.Cells.SpecialCells(ExcelInterop.XlCellType.xlCellTypeLastCell, System.Type.Missing).Row;
int i = 1;
foreach (var prop in sh.GetType().GetProperties())
{
var result = prop.GetValue(sh, null);
oSheet.Cells[rowToUpdate + 1, i] = result == null ? "" : result.ToString();
i++;
}
oBook.Save();
oBook.Close();
oApp.Quit();
//Marshal.ReleaseComObject(oApp);
}