在C#里把Excel中的数据复制到Word中,dll都加好了却总是出现错误:
“System.TypeInitializationException”类型的未经处理的异常在 Spire.XLS.dll 中发生
其他信息: “spr1055”的类型初始值设定项引发异常。
复制方法是根据e—iceblue提供的那个方法
static void Main(string[] args)
{
//初始化工作簿的实例并加载示例Excel文件。从工作簿中获取第一个工作表。
//initialize a workbook and load sample excel file
Workbook workbook = new Workbook();
workbook.LoadFromFile(@"C:\Users\Administrator\Desktop\新建文件夹 (2)\FIR_FRIL_NULL_FY3B_VIRRX_1000M_201303230645.xlsx");
Worksheet sheet = workbook.Worksheets[0];
//initialize a word document
Document doc = new Document();
//add a table
Table table = doc.AddSection().AddTable(true);
table.ResetCells(sheet.LastRow, sheet.LastColumn);
for (int r = 1; r <= sheet.LastRow; r++)
{
for (int c = 1; c <= sheet.LastColumn; c++)
{
CellRange xCell = sheet.Range[r, c];
TableCell wCell = table.Rows[r - 1].Cells[c - 1];
//fill data to word table
TextRange textRange = wCell.AddParagraph().AppendText(xCell.NumberText);
//copy font and cell style from excel to word
CopyStyle(textRange, xCell, wCell);
}
}
//set column width of word table
for (int i = 0; i < table.Rows.Count; i++)
{
for (int j = 0; j < table.Rows[i].Cells.Count; j++)
{
table.Rows[i].Cells[j].Width = 60f;
}
}
//workbook.SaveToFile("D:\\sample.pdf", Spire.Xls.FileFormat.PDF);
doc.SaveToFile(@"C:\Users\Administrator\Desktop\新建文件夹 (2)\FIR_FRIL_NULL_FY3B_VIRRX_1000M_201303230645.doc", Spire.Doc.FileFormat.Docx);
System.Diagnostics.Process.Start(@"C:\Users\Administrator\Desktop\新建文件夹 (2)\FIR_FRIL_NULL_FY3B_VIRRX_1000M_201303230645.doc");
}
private static void CopyStyle(TextRange wTextRange, CellRange xCell, TableCell wCell)
{
//copy font stlye
wTextRange.CharacterFormat.TextColor = xCell.Style.Font.Color;
wTextRange.CharacterFormat.FontSize = (float)xCell.Style.Font.Size;
wTextRange.CharacterFormat.FontName = xCell.Style.Font.FontName;
wTextRange.CharacterFormat.Bold = xCell.Style.Font.IsBold;
wTextRange.CharacterFormat.Italic = xCell.Style.Font.IsItalic;
//copy backcolor
wCell.CellFormat.BackColor = xCell.Style.Color;
//copy text alignment
switch (xCell.HorizontalAlignment)
{
case HorizontalAlignType.Left:
wTextRange.OwnerParagraph.Format.HorizontalAlignment = HorizontalAlignment.Left;
break;
case HorizontalAlignType.Center:
wTextRange.OwnerParagraph.Format.HorizontalAlignment = HorizontalAlignment.Center;
break;
case HorizontalAlignType.Right:
wTextRange.OwnerParagraph.Format.HorizontalAlignment = HorizontalAlignment.Right;
break;
}
}