创建Word测试文件

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.IO;
using System.Threading;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Word = Microsoft.Office.Interop.Word;

//Microsoft Word 12.0 Object Library

/// <summary>
        /// 创建测试文件
        /// </summary>
        /// <param name="CheckedInfo"></param>

        public void CreateWordFile(string CheckedInfo)
        {
            string message = "";
            try
            {
                Object Nothing = System.Reflection.Missing.Value;
                if (!Directory.Exists(Server.MapPath("test1")))
                    Directory.CreateDirectory(Server.MapPath("test1"));//创建文件所在目录

                string name = "CNSI_" + DateTime.Now.ToShortDateString() + ".doc";
                object filename = Server.MapPath("test1") + "//" + name;  //文件保存路径
                message = Server.MapPath("test1") + "//" + name;
                Label1.Text = message;
                //创建Word文档
                Word.Application WordApp = new Word.ApplicationClass();
                Word.Document WordDoc = WordApp.Documents.Add(ref Nothing, ref Nothing, ref Nothing, ref Nothing);

                //添加页眉
                WordApp.ActiveWindow.View.Type = Word.WdViewType.wdOutlineView;
                WordApp.ActiveWindow.View.SeekView = Word.WdSeekView.wdSeekPrimaryHeader;
                WordApp.ActiveWindow.ActivePane.Selection.InsertAfter("[页眉内容]");
                WordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight;//设置右对齐
                WordApp.ActiveWindow.View.SeekView = Word.WdSeekView.wdSeekMainDocument;//跳出页眉设置

                WordApp.Selection.ParagraphFormat.LineSpacing = 15f;//设置文档的行间距

                //移动焦点并换行
                object count = 14;
                object WdLine = Word.WdUnits.wdLine;//换一行;
                WordApp.Selection.MoveDown(ref WdLine, ref count, ref Nothing);//移动焦点
                WordApp.Selection.TypeParagraph();//插入段落

                //文档中创建表格
                Word.Table newTable = WordDoc.Tables.Add(WordApp.Selection.Range, 12, 3, ref Nothing, ref Nothing);
                //设置表格样式
                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;

                //填充表格内容
                newTable.Cell(1, 1).Range.Text = "产品详细信息表";
                newTable.Cell(1, 1).Range.Bold = 2;//设置单元格中字体为粗体
                //合并单元格
                newTable.Cell(1, 1).Merge(newTable.Cell(1, 3));
                WordApp.Selection.Cells.VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;//垂直居中
                WordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;//水平居中

                //填充表格内容
                newTable.Cell(2, 1).Range.Text = "产品基本信息";
                newTable.Cell(2, 1).Range.Font.Color = Word.WdColor.wdColorDarkBlue;//设置单元格内字体颜色
                //合并单元格
                newTable.Cell(2, 1).Merge(newTable.Cell(2, 3));
                WordApp.Selection.Cells.VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;

                //填充表格内容
                newTable.Cell(3, 1).Range.Text = "品牌名称:";
                newTable.Cell(3, 2).Range.Text = "BrandName";
                //纵向合并单元格
                newTable.Cell(3, 3).Select();//选中一行
                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();
                //插入图片
                /*
                string FileName = "c://Winter.jpg";//图片所在路径
                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;//图片宽度
                WordDoc.Application.ActiveDocument.InlineShapes[1].Height = 100f;//图片高度
                //将图片设置为四周环绕型
                Word.Shape s = WordDoc.Application.ActiveDocument.InlineShapes[1].ConvertToShape();
                s.WrapFormat.Type = Word.WdWrapType.wdWrapSquare;
                */
                newTable.Cell(12, 1).Range.Text = "产品特殊属性";
                newTable.Cell(12, 1).Merge(newTable.Cell(12, 3));
                //在表格中增加行
                WordDoc.Content.Tables[1].Rows.Add(ref Nothing);

                WordDoc.Paragraphs.Last.Range.Text = "文档创建时间:" + DateTime.Now.ToString();//“落款”
                WordDoc.Paragraphs.Last.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight;

 


                WordDoc.SaveAs(ref filename, ref Nothing, ref Nothing, ref Nothing,
                    ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing,
                    ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing, ref Nothing);
                Label1.Text += "导出成功 <a href='test1/" + name + "'>Download</a>";
                //WordDoc.Close(ref Nothing, ref Nothing, ref Nothing);
                //WordApp.Quit(ref Nothing, ref Nothing, ref Nothing);
            }
            catch
            {
                message = "文件导出异常!";
            }

        }
      

<think>我们之前已经安装了PHPWord库,现在用户询问如何创建PHP测试文件来验证PHPWord库的功能。根据之前的步骤,我们已经创建了一个测试文件test.php,并给出了示例代码。用户现在可能想要更详细的说明或者一个更复杂的测试例子。我们将创建一个更详细的测试文件,展示如何添加文本、表格和图片,并保存为Word文档。注意:在CentOS7环境下,我们需要确保PHP已经安装了必要的扩展(如gd用于图片处理,xml、zip等),并且有写入权限。步骤:1.创建PHP文件,例如demo.php2.编写代码,包括:-引入自动加载文件-创建PhpWord对象-添加一个节(section)-在节中添加文本(可以设置字体样式)-添加表格(创建表格,添加行和单元格)-添加图片(使用addImage)3.保存为Word文档同时,我们需要确保有图片文件可供测试。这里假设我们在当前目录下有一张名为"centos_logo.png"的图片。如果用户没有现成的图片,我们可以提醒用户准备一张,或者使用代码创建一张(但这样比较复杂,不如直接建议用户放置一张图片)。代码示例:</think>### CentOS 7 创建 PHPWord 测试文件教程 以下是创建 PHPWord 测试文件的详细步骤,包含验证库功能的完整示例: #### 步骤1:创建测试文件 ```bash # 进入项目目录 cd phpword_project # 创建测试文件(使用 nano 编辑器) nano phpword_test.php ``` #### 步骤2:编写测试脚本 将以下代码复制到文件中(支持文本、表格、图片功能验证): ```php <?php require_once 'vendor/autoload.php'; use PhpOffice\PhpWord\PhpWord; use PhpOffice\PhpWord\IOFactory; use PhpOffice\PhpWord\Style\Font; // 1. 创建文档对象 $phpWord = new PhpWord(); // 2. 添加章节 $section = $phpWord->addSection(); // 3. 添加文本(验证基础功能) $section->addText( 'PHPWord 功能验证 - CentOS 7', ['name' => 'Arial', 'size' => 16, 'bold' => true] ); $section->addText("当前时间: ".date('Y-m-d H:i:s')); // 4. 添加表格(验证复杂结构) $table = $section->addTable(['borderSize' => 6]); $table->addRow(); $table->addCell(1500)->addText('组件'); $table->addCell(2500)->addText('状态'); $table->addCell(2000)->addText('版本'); $table->addRow(); $table->addCell()->addText('PHP'); $table->addCell()->addText('运行正常', ['color' => '006600']); $table->addCell()->addText(phpversion()); $table->addRow(); $table->addCell()->addText('PHPWord'); $table->addCell()->addText('已加载'); $table->addCell()->addText('0.18+'); // 5. 添加图片(验证多媒体支持) $section->addTextBreak(2); // 空两行 $section->addText('系统验证图片:'); $imagePath = __DIR__.'/centos_logo.png'; if(file_exists($imagePath)) { $section->addImage($imagePath, [ 'width' => 150, 'height' => 150, 'alignment' => 'center' ]); } else { $section->addText('图片未找到,请创建centos_logo.png'); } // 6. 保存文档 $filename = 'phpword_test_'.date('YmdHis').'.docx'; $objWriter = IOFactory::createWriter($phpWord, 'Word2007'); $objWriter->save($filename); echo "✅ 测试文件生成成功: ".$filename.PHP_EOL; echo "✅ PHPWord 功能验证通过!"; ?> ``` #### 步骤3:创建测试图片(可选) ```bash # 生成 CentOS 标识图片(需要安装ImageMagick) sudo yum install ImageMagick -y convert -size 200x200 xc:white -fill '#263238' \ -draw 'circle 100,100 100,10' -pointsize 24 \ -fill white -gravity center -annotate 0 'CentOS\n7' \ centos_logo.png ``` #### 步骤4:运行测试 ```bash php phpword_test.php ``` 成功输出: ``` ✅ 测试文件生成成功: phpword_test_202310051200.docx ✅ PHPWord 功能验证通过! ``` #### 验证结果 1. 检查生成的 `.docx` 文件: ```bash ls -lh *.docx ``` 2. 将文件下载到本地用 Word 打开,应包含: - 标题文本 - 包含三列的表格 - CentOS 标识图片(如已创建) - 当前时间戳 #### 常见问题解决 1. **图片加载失败**: - 确保 `centos_logo.png` 文件存在 - 安装 GD 库:`sudo yum install php-gd`[^1] - 重启 web 服务:`sudo systemctl restart httpd` 2. **字体不显示**: ```php // 添加中文字体支持 $font = new Font(); $font->setName('SimSun'); // 宋体 $section->addText('中文测试', $font); ``` 3. **权限错误**: ```bash chmod 755 . # 确保当前目录可写 ``` > 提示:测试完成后,可通过 `unzip -l 文件名.docx` 检查文档内部结构[^1]
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值