Asp.net dynamically generates Word documents and fills in data for conversion

Source: Internet
Author: User

From http://hi.baidu.com/huyuan2008

Good stuff.

"

The procedure is as follows:

First, add reference:

1. Add reference-> COM-> Microsoft Word 11.0 Object Library (Be sure not to select Microsoft Office 11.0 Object by mistake
Library, I wasted a long time because of this low-level error .)

2. Add using Word to the. cs file;

The Code is as follows:

 

Public string CreateWordFile (string CheckedInfo)
{
String message = "";
Try
{
Object Nothing = System. Reflection. Missing. Value;
Directory. CreateDirectory ("C:/CNSI"); // Directory where the file is created
String name = "CNSI.doc ";
Object filename = "C: // CNSI //" + name; // file storage path
// Create a Word document
Word. Application WordApp = new Word. ApplicationClass ();
Word. Document WordDoc = WordApp. Documents. Add (ref Nothing, ref Nothing );

// Add a header
WordApp. ActiveWindow. View. Type = WdViewType. wdOutlineView;
WordApp. ActiveWindow. View. SeekView = WdSeekView. wdSeekPrimaryHeader;
WordApp. ActiveWindow. ActivePane. Selection. InsertAfter ("[header content]");
WordApp. Selection. ParagraphFormat. Alignment = Word. WdParagraphAlignment. wdAlignParagraphRight; // set the right Alignment
WordApp. ActiveWindow. View. SeekView = WdSeekView. wdSeekMainDocument; // jump out of the header settings

WordApp. Selection. ParagraphFormat. LineSpacing = 15f; // set the line spacing of the document.

/* WordDoc. PageSetup. Orientation = Word. WdOrientation. wdOrientLandscape; // set the page to portrait
WordDoc. PageSetup. PageHeight = WordApp. CentimetersToPoints (21F );
WordDoc. PageSetup. PageWidth = WordApp. CentimetersToPoints (29.7F );
WordDoc. PageSetup. TopMargin = 57; // you can specify the top margin.
WordDoc. PageSetup. BottomMargin = 57; // sets the bottom margin.
WordDoc. PageSetup. LeftMargin = 57; // set the left margin
WordDoc. PageSetup. RightMargin = 57; // set the right margin */

// Move the focus and wrap the line
Object count = 14;
Object WdLine = Word. WdUnits. wdLine; // change the line;
WordApp. Selection. MoveDown (ref WdLine, ref count, ref Nothing); // move the focus
WordApp. Selection. TypeParagraph (); // insert a paragraph

// Create a table in the document
Word. Table newTable = WordDoc. Tables. Add (WordApp. Selection. Range, 12, 3, ref Nothing, ref Nothing );
// Set the table style
NewTable. Borders. OutsideLineStyle = Word. WdLineStyle. wdLineStyleThickThinLargeGap;
NewTable. Borders. InsideLineStyle = Word. WdLineStyle. wdLineStyleSingle;
NewTable. Columns [1]. Width = 100f;
NewTable. Columns [2]. Width = 220f;
NewTable. Columns [3]. Width = 105f;

// Fill in the table content
NewTable. Cell (1, 1). Range. Text = "product details table ";
NewTable. Cell (1, 1). Range. Bold = 2; // set the font of the Cell to Bold.
// Merge Cells
NewTable. Cell (1, 1). Merge (newTable. Cell (1, 3 ));
WordApp. Selection. Cells. VerticalAlignment = Word. wdcellverticalignment. wdCellAlignVerticalCenter; // vertically centered
WordApp. Selection. ParagraphFormat. Alignment = Word. WdParagraphAlignment. wdAlignParagraphCenter; // horizontally centered

// Fill in the table content
NewTable. Cell (2, 1). Range. Text = "Basic Product Information ";
NewTable. Cell (2, 1). Range. Font. Color = Word. WdColor. wdColorDarkBlue; // set the Font Color in the Cell.
// Merge Cells
NewTable. Cell (2, 1). Merge (newTable. Cell (2, 3 ));
WordApp. Selection. Cells. verticalignment = Word. wdcellverticalignment. wdCellAlignVerticalCenter;

// Fill in the table content
NewTable. Cell (3, 1). Range. Text = "brand name :";
NewTable. Cell (3, 2). Range. Text = CheckedInfo;
// Vertically merge Cells
NewTable. Cell (3, 3). Select (); // Select a row
Object moveUnit = Word. WdUnits. wdLine;
Object moveCount = 5;
Object moveExtend = Word. WdMovementType. wdExtend;
WordApp. Selection. MoveDown (ref moveUnit, ref moveCount, ref moveExtend );
WordApp. Selection. Cells. Merge ();
// Insert an image
String FileName = @ "C: \ 1.jpg"; // path of the image
Object LinkToFile = false;
Object SaveWithDocument = true;
Object Anchor = WordDoc. Application. Selection. Range;
WordDoc. Application. ActiveDocument. InlineShapes. AddPicture (FileName, ref LinkToFile, ref SaveWithDocument, ref Anchor );
WordDoc. Application. ActiveDocument. InlineShapes [1]. Width = 100f; // Image Width
WordDoc. Application. ActiveDocument. InlineShapes [1]. Height = 100f; // Image Height
// Set the image to a peripheral image
Word. Shape s = WordDoc. Application. ActiveDocument. InlineShapes [1]. ConvertToShape ();
S. WrapFormat. Type = Word. WdWrapType. wdWrapSquare;

NewTable. Cell (12, 1). Range. Text = "special properties ";
NewTable. Cell (12, 1). Merge (newTable. Cell (12, 3 ));
// Add rows to the table
WordDoc. Content. Tables [1]. Rows. Add (ref Nothing );

WordDoc. Paragraphs. Last. Range. Text = "document creation time:" + DateTime. Now. ToString (); // "pay-as-you-go"
WordDoc. Paragraphs. Last. Alignment = Word. WdParagraphAlignment. wdAlignParagraphRight;

// Save the file
WordDoc. saveAs (ref filename, ref Nothing, ref Nothing, ref Nothing, ref Nothing );
WordDoc. Close (ref Nothing, ref Nothing, ref Nothing );
WordApp. Quit (ref Nothing, ref Nothing, ref Nothing );
Message = name + "the document is generated successfully and saved to C: CNSI ";
}
Catch
{
Message = "An error occurred while exporting the file! ";
}
Return message;
}

Note the following points:

1. When adjusting the position of the content in the merged cell, I first wrote data to the cell, then selected the cell, then merged the cell, and finally adjusted the horizontal and vertical positions. However, no matter how I adjust the position, the cell content is always shown at the bottom. After some attempts, I found that we should first merge cells, then add data to the merged cells, then select the merged cells, and finally set the horizontal and vertical positions. This is feasible. Example:

NewTable. Cell (12,
1). Merge (newTable. Cell (18, 1 ));
NewTable. Cell (12, 1). Range. Text =
"Example ";
NewTable. Cell (12, 1). Select ();

WordApp. Selection. Cells. verticalignment =
Word. WdCellVerticalAlignment. wdCellAlignVerticalCenter; // center vertically

WordApp. Selection. ParagraphFormat. Alignment =
Word. WdParagraphAlignment. wdAlignParagraphCenter; // horizontally centered

2. Before a website is published, the Word export operation is normal, but an exception occurs after the website is published. This may be a permission issue. The simplest solution is in <system. web> </system. add the following statement between web and web:

<Identity impersonate = "true"
UserName = "your account" password = "password"/>. Note that the password cannot be empty or weak.

3. If the following error occurs:

"Word cannot save this file because it has been opened elsewhere. (C: \... \ STARTUP \ Powerword. dot )"

Or

"Caught COMException

The message filter shows that the application is in use. (Exception from HRESULT: 0X8001010A (RPC_E_SERVERCALL_RETRYLATER ))

"

Please refer to the winword.exe process.

"

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.