2

在我的应用程序中,我已将空白 excel 文件表单的副本保存为资源,我需要加载此文件,修改其两个工作表,并以新名称将其保存在新位置。用户不应该看到该过程。

我将 C# 2010 与 SQL 服务器一起使用,我将从该服务器加载我的数据并将其放入 excel 表单中。

感谢您的时间。

4

3 回答 3

5

使用可以在 .NET 或 COM (Microsoft.Office.Interop.Excel) 中找到的 Microsoft 互操作程序集,然后将所有需要的单元格加载到 a 中List并修改数据。

像这样的东西(下面的代码):

 string path = @"C:\temp\test.xls";
   ApplicationClass excelApllication = null;
   Workbook excelWorkBook = null;
   Worksheet excelWorkSheet = null;

   excelApllication = new ApplicationClass();
   System.Threading.Thread.Sleep(2000);
   excelWorkBook = excelApllication.Workbooks.Add();
   excelWorkSheet = (Worksheet)excelWorkBook.Worksheets.get_Item(1);
   // Attention: 1 indexed cells, [Row, Col]
   excelWorkSheet.Cells[1, 1] = "Column A, Row 1";
   excelWorkSheet.Cells[2, 5] = "Column E, Row 2";
   excelWorkSheet.Cells[3, 3] = "Column C, Row 3";

   excelWorkBook.SaveAs(path, XlFileFormat.xlWorkbookNormal);

   excelWorkBook.Close();
   excelApllication.Quit();

   Marshal.FinalReleaseComObject(excelWorkSheet);
   Marshal.FinalReleaseComObject(excelWorkBook);
   Marshal.FinalReleaseComObject(excelApllication);
   excelApllication = null;
   excelWorkSheet = null;
   //opens the created and saved Excel file
   Process.Start(path);

这应该发生在线程内部,因为您不希望用户注意到该任务。

http://msdn.microsoft.com/en-us/library/aa645740%28v=vs.71%29.aspx (线程教程)

于 2012-10-15T14:31:00.663 回答
0

如果可能的话,我会尽量避免使 Excel 自动化,并使用 OpenXML SDK(或包装 OpenXML SDK 的库)来完成这项任务。

是一篇可以帮助您入门的文章。

于 2012-10-15T14:24:30.747 回答
0

我想你想这样做……至少对我有用。:)

    private void btnExcel_Click(object sender, EventArgs e)
    {
        string newDirectoryPath = ValidateDirectory();
        string newFilePath = Path.Combine(newDirectoryPath, "new.xls");

        //brand new temporary file
        string tempPath = System.IO.Path.GetTempFileName();
        //to manage de temp file life
        FileInfo tempFile = new FileInfo(tempPath);
        //copy the structure and data of the template .xls
        System.IO.File.WriteAllBytes(tempPath,Properties.Resources.SomeResource);

        Excel.Application xlApp;  
        Excel.Workbook xlWorkBook;
        Excel.Worksheet xlWorkSheet;
        object misValue = System.Reflection.Missing.Value;

        xlApp = new Excel.Application();
        xlWorkBook = xlApp.Workbooks.Open(tempPath, 0, true, 5, "", "", true, Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
        xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

        //WorkTheExcelFile();

        tempFile.Delete();

        xlWorkBook.SaveAs(newFilePath);
        xlWorkBook.Close(true, misValue, misValue);
        xlApp.Quit();

        releaseObject(xlWorkSheet);
        releaseObject(xlWorkBook);
        releaseObject(xlApp);

        Process.Start(newFilePath + ".xlsx");
    }
于 2014-08-05T00:51:57.443 回答