日期:2014-05-17  浏览次数:20972 次

C#生成Excel 2007文件并下载
添加引用Microsoft Excel 12.0 Object Library,我这里使用的是Office 2007。

有必要的话,需要修改web.config:
<identity impersonate="true" userName="administrator" password="password"/>
目的是使用这个账号来运行Excel程序,曾经使用Word 2007在代码中生成XPS文件,因为没有如此修改web.config,初始化Word程序时,得到无权限的异常或者弹出Windows登陆框。

代码如下:

public void exceport()
        {
            Application app = null;
            Workbook wb = null;
            Worksheet sheet = null;

            try
            {
                //保存到web临时目录
                //string path = @"D:\" + DateTime.Now.ToString(@"yyyy-MM-dd-HHmmss") + ".xlsx";
                app = new Application();
                app.Visible = false;

                wb = (Workbook)app.Workbooks.Add(Missing.Value);
                sheet = (Worksheet)wb.ActiveSheet;

                List<String[]> contents = new List<string[]>();
                string[] A = { "123", "hwt", "xyz"};
                contents.Add(A);
                string[] B = { "456", "tyu", "abc"};
                contents.Add(B);

                for (int i = 0; i < contents.Count; i++)
                {
                    String[] item = contents[i];

                    for (int j = 0; j < item.Length; j++)
                        sheet.Cells[i + 1, j + 1] = item[j];
                }
                wb.Saved = true;

                string fileName = String.Format("{0}{1}.xlsx", System.AppDomain.CurrentDomain.BaseDirectory, DateTime.Now.Ticks);
                app.ActiveWorkbook.SaveCopyAs(fileName);

                //return fileName;
            }
            finally
            {
                wb.Close(null, null, null);
                app.Workbooks.Close();
                app.Quit();
                Marshal.ReleaseComObject((object)app);
                Marshal.ReleaseComObject((object)wb);
                Marshal.ReleaseComObject((object)sheet);
                GC.Collect();