Como escrever excel, abrindo-programaticamente com Microsoft.Office.Interop.Excel dll?

StackOverflow https://stackoverflow.com/questions/1648125

  •  22-07-2019
  •  | 
  •  

Pergunta

Eu quero usar Microsoft.Office.Interop.Excel dll para escrever os dados em folha de excel. Eu tenho um código:

if (System.IO.File.Exists(strFileName))
{
    System.IO.File.SetAttributes(strFileName, FileAttributes.Normal);
    System.IO.File.Delete(strFileName);
}

// Open an instance of excel. Create a new workbook.
// A workbook by default has three sheets, so if you just want 
//a single one, delete sheet 2 and 3

Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
Excel._Workbook xlWB = (Excel._Workbook)xlApp.Workbooks.Add(Missing.Value);

Excel._Worksheet xlSheet = (Excel._Worksheet)xlWB.Sheets[1];
((Excel._Worksheet)xlWB.Sheets[2]).Delete();
((Excel._Worksheet)xlWB.Sheets[2]).Delete();

xlSheet.Name = strSheetName;

// Write a value into A1
xlSheet.Cells[2, 1] = "Tags";
xlSheet.Cells[2, 2] = "Leak Test";
xlSheet.Cells[2, 3] = "FIR";
xlSheet.Cells[2, 4] = "SOP";

xlWB.SaveAs(strFileName, Missing.Value, Missing.Value, Missing.Value, 
Missing.Value,Missing.Value, 
Microsoft.Office.Interop.Excel.XlSaveAsAccessMode.xlNoChange, Missing.Value, 
Missing.Value, Missing.Value, Missing.Value, Missing.Value);
xlApp.Quit();

// Release the COM object, set the Excel variables to Null, and tell the 
//Garbage Collector to do its thing
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlSheet);
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlWB);
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp);

xlSheet = null;
xlWB = null;
xlApp = null;

Agora eu quero abrir o arquivo do Excel existente do caminho e, em seguida, colocar os alguns dados para a folha de excel que nós nome fornecido e, em seguida, ele será salvo no caminho específico de programação.

Por favor me responda à origem se qualquer que pode abrir o arquivo do Excel existente e que pode ser de acréscimo e salvar com outro nome.

Saudações, Girish

Foi útil?

Solução

Consulte aqui para informações .

Outras dicas

ExcelPackage não é mais mantido. Parece ter alguns bugs. Lendo comentário lá, eu encontrei http://epplus.codeplex.com/

É construído em cima ExcelPackage e herdá-la licenças (GPL), por isso não podem atender às suas necessidades.

Se você estiver usando a versão 2007 do Excel, eu recomendo usar ExcelPackage vez - é uma implementação do padrão OpenXML, é muito mais rápido e muito menos confuso do que interoperabilidade, e você pode executá-lo em uma máquina que não tem sequer Excel (Office) instalado, como em seu servidor web.

Altamente recomendado -. Mas limitado para o Excel 2007 e para cima

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top