Somebody
Somebody

Reputation: 2789

generate an excel file from template in asp.net

I have a desktop app in which I generate an excel file from a template, basically what I do is to make a copy of the template excel file to a new directory, open it, and add records to it.

this is a code snippet:

string ExcelFiles = txtFileOutput.Text; //Application.StartupPath + @"\ExcelFiles\"; 
        string DestFile = ExcelFiles + FinalListOfTrucks[0].Date.ToShortDateString().Replace('/', '_') + ".xlsx"; 
        if (File.Exists(DestFile))
        {
            try
            {
                File.Delete(DestFile);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error deleting file: " + ex.Message);
            }
        }

        try
        {
            File.Copy(Application.StartupPath + @"\ExcelTemplate.xlsx", DestFile);
        }
        catch (Exception ex)
        {
            MessageBox.Show("Error copying file: " + ex.Message);
        }

        string appPath = Path.GetDirectoryName(Application.ExecutablePath);            
        string strConnectionXls = "Provider=Microsoft.ACE.OLEDB.12.0;" + "Data Source=" + DestFile + ";Extended Properties=Excel 12.0;";
        OleDbConnection cno = new OleDbConnection(strConnectionXls);
        OleDbCommand cmo = new OleDbCommand();
        cmo.Connection = cno;
        cmo.CommandType = CommandType.Text;

string QueryHeader = "INSERT INTO [RptTotal$] (NUMERO,FECHA,JORNADA,PLACA,HORA_DE_LLEGADA,HORA_FIN_CARGUE,HORA_FIN_DESCARGUE,VOLUMEN,DISTANCIA,TIPO_DE_VEHICULO,MATERIAL,MISSED_DATE)";

cmo.CommandText = QueryHeader + " VALUES ('" + No.ToString() + "','" + Fecha + "','" + Jornada + "','" + Placa + "','" + HoraDeLlegada + "','" + HoraFinCargue + "','" +
                                                        HoraFinDescargue + "','" + Volumen + "','" + Distancia + "','" + TipoDeVehiculo + "','" + Material + "','" + MissedDate + "')";
                cmo.ExecuteNonQuery();

Now, let's say that I can Add a folder to my webapp, and place the excel template there, how to start from there to achieve the same functionality in web :\ ?

Upvotes: 0

Views: 2251

Answers (1)

Emmanuel N
Emmanuel N

Reputation: 7449

Same thing you are doing on your desktop application, just need to clean up your code.

  1. Copy template, save templete same where in your server
  2. Need to remove all message boxes
  3. Use OleDbConnection to modify your excel file( would strongly recommed OpenXML or libraries build on top of openXML like Epplus)
  4. Save changes
  5. Stream the file to client
  6. Figure out how to clean streamed files

Upvotes: 1

Related Questions