在我的应用程序中,我保存了一份空白excel文件格式的副本作为资源,我需要加载此文件,修改其两个工作表,将其保存在具有新名称的新位置。 用户不应该看到这个过程。
我正在使用带有SQL服务器的C#2010,我将从中加载我的数据并将其放入excel表单。
谢谢你的时间。
答案 0 :(得分:4)
使用可在.NET或COM中找到的Microsoft Interop程序集(Microsoft.Office.Interop.Excel)
然后将所有必需的单元格加载到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);
这应该发生在Thread内部,因为您不希望用户注意到该任务。
http://msdn.microsoft.com/en-us/library/aa645740%28v=vs.71%29.aspx (线程教程)
答案 1 :(得分:1)
到目前为止你做了什么?
以下两个链接应该有所帮助:
答案 2 :(得分:0)
如果可能的话,我会尽量避免自动化Excel,并使用OpenXML SDK(或包装OpenXML SDK的库)来执行此任务。
Here是一篇可以帮助您入门的文章。
答案 3 :(得分: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");
}