6. 将下面的程序加入到method:static void Main(string[] args)中;为避免手工输入这些语句,可以通过插入代码段 | My Code Snippets | OpenDocument
string docName = @"CreateDocFromDatabase.docx";
// Reuse style info from template
File.Copy(@"Template.docx", docName, true);
using (WordprocessingDocument myDoc = WordprocessingDocument.Open(docName, true))
{
}
备注:这一步,我们拷贝一个空文档到debug路径下,给其一个名字,并且用SDK打开文档
7. 将下面的程序加入到method Main() 中的using (WordprocessingDocument myDoc = WordprocessingDocument.Open(docName, true)) {}中;为避免手工输入这些语句,可以通过插入代码段 | My Code Snippets | CreateTable
MainDocumentPart mainPart = myDoc.MainDocumentPart;
Document doc = mainPart.Document;
// Connect to databse
AdventureWorksDataContext db = new AdventureWorksDataContext();
// Create table and add properties
Table table = new Table();
// Header strings for table
string[] headerContent = new[] { "Name", "Subcategory", "Price", "Image" };
// Create row
TableRow header = CreateRow(headerContent, null);
table.AppendChild(header);
备注:这一步,我们生成一个LINQ to SQL类的instance – AdventureWorksDataContext。我们有生成一个Table object。
8. 将以下程序直接加到上一段程序后面;为避免手工输入这些语句,可以通过插入代码段 | My Code Snippets | QueryDB
int i = 1;
foreach (var product in productQuery)
{
foreach (var item in product)
{
// insert your next code snippet here
}
}
备注:在这一步,我们从AdventureWorks2008 LINQ to SQL类连到AdventureWorks2008数据库,并从中读取数据出来。
9. 将以下程序直接加到上一段程序的inner foreach loop里;为避免手工输入这些语句,可以通过插入代码段 | My Code Snippets | ProcessProduct
if (item.ListPrice != 0)
{
// Get data from query
price += Math.Round(item.ListPrice, 2);
string imgId = "rIdImg" + i;
i++;
string[] content = new[] { item.Name,
item.ProductSubcategoryID == null ? null : item.ProductSubcategory.Name,
price };
// Insert the next code snippet here
}
备注:在这一步中,每个产品的价格被四舍五入到小数点后两位。每个产品的Image 都生成一个id。我们也生成一个字串列string array来存储每个产品的名称(name),副类(Subcategory)和价格(price)。
10. 将以下程序直接加到上一段程序的后面,但是要在‘if’语句里面; 为避免手工输入这些语句,可以通过插入代码段 | My Code Snippets | ProcessProductImage
ImagePart imagePart = mainPart.AddImagePart(ImagePartType.Gif, imgId);
// Stream image into image part
imagePart.FeedData( new MemoryStream( item.ProductProductPhoto.First().ProductPhoto.LargePhoto.ToArray()));
// Calculate image size for xml
Bitmap bitmap = new Bitmap( new MemoryStream( item.ProductProductPhoto.First().ProductPhoto.LargePhoto.ToArray()));
int widthInEmu, heightInEmu;
CalculateEmus(bitmap, out widthInEmu, out heightInEmu);
// Create a new drawing object based on xml
Drawing d = GenerateDrawing(imgId, item.ProductProductPhoto.First().ProductPhoto.LargePhotoFileName, widthInEmu, heightInEmu);
备注:在这一步中,我们生成了一个ImagePart 的instance,它的类是Gif。它的内容是从数据库中取来的。我们也生成了一个Bitmap对象。同样它里面的数据也是通过计算图形文档的高和宽而得来的。然后我们生成一个Drawing对象,并设置它指向刚才生成的ImagePart的instance。
11. 将以下程序直接加到上一段程序的后面,但是要在‘if’语句里面; 为避免手工输入这些语句,可以通过插入代码段 | My Code Snippets | AddRow
TableRow tr = CreateRow(content, d);
table.AppendChild(tr);
备注:在这一步中,我们生成一个TableRow对象,并把它加到最后我们要生成的文档中。到此,我们已经完成了处理每一个TableRow的步骤。