1. 程式人生 > >C#也能動態生成Word文件並填充資料, 匯出EXCEL 方法

C#也能動態生成Word文件並填充資料, 匯出EXCEL 方法

        public string CreateWordFile(string CheckedInfo)
        ...{
            string message = "";
            try
            ...{
                Object Nothing = System.Reflection.Missing.Value;
                Directory.CreateDirectory("C:/CNSI");  //建立檔案所在目錄
                string name = "CNSI_" + DateTime.Now.ToShortString()+".doc";
                object filename = "C://CNSI//" + name;  //檔案儲存路徑
                //建立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 = WdViewType.wdOutlineView;
                WordApp.ActiveWindow.View.SeekView = WdSeekView.wdSeekPrimaryHeader;
                WordApp.ActiveWindow.ActivePane.Selection.InsertAfter("[頁首內容]");
                WordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight;//設定右對齊
                WordApp.ActiveWindow.View.SeekView = 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 = Picture;//圖片所在路徑
                   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);
                    WordDoc.Close(ref Nothing, ref Nothing, ref Nothing);
                    WordApp.Quit(ref Nothing, ref Nothing, ref Nothing);
                    message=name+"文件生成成功,以儲存到C:CNSI下";
            }
            catch
            ...{
                message = "檔案匯出異常!";
            }
            return message;
        }

是用WPF將資料匯出成EXCEL其實和其他.NET應用是相通的,ASP.NET也好WINFORM也好,都是用相同的方法實現,唯一不同的是ASP.NET中可能會存在使用者許可權的問題,畢竟ASP.NET的執行使用者是IIS指定的使用者而不是預設的系統使用者。

具體實現方法如下,程式碼中使用完整的名稱空間,便於理解

第一步,不許引用Excel的程式集,不同於網上其他文章,我直接引用了.NET裡的Microsoft.Office.interop.Excel ,而不是在Com裡引用Microsoft Excel ,安裝好VS08或.NET框架包以後 .NET本身就有這個程式集,不用去引用系統中安裝的OFFICE的程式集,當然兩種引用都是相同效果的。

然後就可以直接編寫程式碼了

            DataOperation dataop = new DataOperation();

            DataView dv = dataop.OpertaionsGet(); //獲得一個dataview,這是我的程式裡的方法,這裡可以隨便獲得任何一個dataview或者其他資料集合sheet

            dataop.Clear();

            Microsoft.Office.Interop.Excel.ApplicationClass ac = new Microsoft.Office.Interop.Excel.ApplicationClass();

            Microsoft.Office.Interop.Excel.Workbook wb ; //這裡千萬不能使用 new 來例項物件,不然會異常

            Microsoft.Office.Interop.Excel.Worksheet ws ;

            wb = ac.Workbooks.Add(System.Reflection.Missing.Value);  //建立工作簿(WorkBook:即Excel檔案主體本身)

            ws = (Microsoft.Office.Interop.Excel.Worksheet)wb.Worksheets.Add(System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value);        //建立工作表(Worksheet:工作表,即Excel裡的子表sheet)

            //設定表名

            ws.Name = "TestXlS";

            //將資料匯入到工作表的單元格

            for (int i = 0; i < dv.Count; i++)

            {

                for(int j=0;j<dv.Table.Columns.Count;j++)

                ws.Cells[i+1,j+1]= dv[i][j].ToString();

            }

            //儲存到檔案

            wb.SaveAs("D://aa1.xls", System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value);

            //關閉

            wb.Close(System.Reflection.Missing.Value, System.Reflection.Missing.Value, System.Reflection.Missing.Value);

其實很簡單,如同將一個數據表格匯入到另一個數據表格一樣,只需要注意Excel的方法中的引數。

本示例中,大部分引數都採用預設,System.Reflection.Missing.Value,在儲存方法中只有第1個引數必須是完整儲存路徑字串和第7個引數是XlSaveAsAccessMode列舉。

還有一個必須要注意的地方,WorkSheet單元Cell的索引是從1開始的,不同於我們習慣的從0開始,因此在Cells二維陣列中程式碼是ws.Cells[i+1,j+1]這個樣的。

最後,關閉工作表 ,這個容易理解,否者,儲存的檔案將一直被Excel程序佔用。

另外有時候數字文字會被用科學計數法顯示,格式化數字為文字的方法是

ws.Cells.NumberFormat = "@";