Wpf Excel Import and Export Data

Posted by jacobelias on Thu, 23 May 2019 00:23:56 +0200

Turn: http://blog.csdn.net/sanjiawan/article/details/6818921
Microsoft's import and export methods are basically the same whether they are asp.net, winform, or wpf. It's all about instantiating Excel classes, creating workbooks, creating worksheets, and then saving or extracting data. So easy to operate that feeling has become a matter of course.

PS: The following is based on VS2010+Framework 4.0
Let's first look at how wpf exports data to Excel files.
Export data to Excel
First, the component Microsoft.Office.Interop.Excel of. net 4.0 is referenced.
"
using Microsoft.Office.Interop.Excel;

private void btnExport_Click(object sender, RoutedEventArgs e)
{

       //First, we simulate the creation of the data to be exported, which is stored in the DataTable.

       System.Data.DataTable dt = new System.Data.DataTable();
        dt.Columns.Add("ID", typeof(int));
        dt.Columns.Add("NickName", typeof(string));
        dt.Columns.Add("QNumber", typeof(string));

        DataRow row = dt.NewRow();
        row["ID"] = 1;
        row["NickName"] = "sanjiawan";
        row["QNumber"] = "12345678";
        dt.Rows.Add(row);

        row = dt.NewRow();
        row["ID"] = 2;
        row["NickName"] = "Character 2";
        row["QNumber"] = "9058307";
        dt.Rows.Add(row);

        //Create Excel

        Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();
        Workbook excelWB = excelApp.Workbooks.Add(System.Type.Missing);    //Create a workbook (WorkBook: Excel file body itself)
          Worksheet excelWS = (Worksheet)excelWB.Worksheets[1];   //Create a worksheet (that is, a subsheet in Excel) 1 to represent data export in the subsheet 1

        //ExceelWS.Cells.NumberFormat="@";//If there is a numeric type in the data, it can be displayed in a different text format.
        //Import data into the cells of the worksheet
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            for (int j = 0; j < dt.Columns.Count; j++)
            {
                excelWS.Cells[i + 1, j + 1] = dt.Rows[i][j].ToString();   //Excel cells begin with index 1
            }
        }

        excelWB.SaveAs("D:\\sanjiawan.xlsx");  //Save it to the specified path
          excelWB.Close();
        excelApp.Quit();  //Kill AllExcel (excelApp); Release processes that may not have been released
    }
Note: Because we have used Microsoft.Office.Interop.Excel as a component, some of the class names will be the same as those in System.Data, which makes it easy for the program to report errors when running. So what we need to do is refine which components these classes belong to, just like System.Data.DataTable above. You don't have to worry about not being familiar with the names of these components. VS2010 will give intelligent hints.
Sometimes Excel takes up a process for a long time, so we need to release the process.

region releases Excel processes

    public bool KillAllExcel(Microsoft.Office.Interop.Excel.Application excelApp)
    {
        try
        {
            if (excelApp != null)
            {
                excelApp.Quit();
                System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp);
                //Releasing COM components is actually reducing their reference count by 1   
                //System.Diagnostics.Process theProc;   
                foreach (System.Diagnostics.Process theProc in System.Diagnostics.Process.GetProcessesByName("EXCEL"))
                {
                    //Close the graphics window first. If the shutdown fails, sometimes you can't see the excel of the graphics window in the state.   
                    //But there is still an EXCEL.EXE process in the process, so it needs to be released.   
                    if (theProc.CloseMainWindow() == false)
                    {
                        theProc.Kill();
                    }
                }
                excelApp = null;
                return true;
            }
        }
        catch
        {
            return false;
        }
        return true;
    }

#endregion

From the above code, it's natural to do it. Excel If we need to design the export style, we can also use the following code.
//Style Design for Exporting Excel
Microsoft.Office.Interop.Excel.Application excelApp = new Microsoft.Office.Interop.Excel.Application();
Workbook excelWB = excelApp.Workbooks.Add(System.Type.Missing);//Create a workbook (WorkBook: Excel file body itself)
Worksheet excelWS = (Worksheet)excelWB.Worksheets[1];//Create a worksheet (that is, a subsheet in Excel) 1 to represent data export in the subsheet 1
Range range = null;

#region table property settings
excelWS.Name = "sanjiawan"; //Setting the name of the worksheet
range = (Range)excelWS.get_Range("A1", "E1"); //Get multiple Excel cell areas: This example acts as Excel header 
range.Merge(0); //Unit merge action should be designed with get_Range() above.

excelWS.Cells[1, 1] = "Excel Cell assignment"; //Excel cell assignment 

range.Font.Size = 15; //Set font size

range.Font.Underline = true; //Set whether the font is underlined

range.Font.Name="Blackbody"; //Types of fonts set 

range.HorizontalAlignment=XlHAlign.xlHAlignCenter; //How fonts are set in cells 

range.ColumnWidth=15; //Set the width of the cell 

range.Cells.Interior.Color = System.Drawing.Color.FromArgb(255, 204, 153).ToArgb(); //Setting the background of the cell 

range.Borders.LineStyle=1; //Set the thickness of cell borders 

range.BorderAround(XlLineStyle.xlContinuous, XlBorderWeight.xlThick, XlColorIndex.xlColorIndexAutomatic, System.Drawing.Color.FromArgb(255, 204, 153).ToArgb()); //Border cells 

range.Borders.get_Item(Microsoft.Office.Interop.Excel.XlBordersIndex.xlEdgeTop).LineStyle = Microsoft.Office.Interop.Excel.XlLineStyle.xlLineStyleNone; //Set the top border of the cell to be borderless 

range.EntireColumn.AutoFit(); //Automatic adjustment of column width 

range.WrapText = true; //Automatic Line Breaking of Text 

range.Interior.ColorIndex = 39; //Filling color is light purple 

range.Font.Color = System.Drawing.Color.FromArgb(255, 204, 153).ToArgb(); //Font color 

excelApp.DisplayAlerts = false; //When saving Excel, save it directly without popping up a window that is saved or not. 
#endregion





//If we need to use the above styles, we also have a way to export them to Range's style design.  

//The following code can replace the "Import data into the cells of the worksheet" operation above.
  Range range = null;
  range = excelWS.get_Range("A1", System.Type.Missing);  //Set the position of the top left corner of the table to start displaying
  for (int i = 0; i < table.Rows.Count; i++)
  {
       for (int j = 0; j < table.Columns.Count; j++)
       {
            range.get_Offset(i, j).Cells.Value = table.Rows[i][j].ToString();
       }
  }

//That's all for export. Next, let's look at how the data in Excel file is imported into the program.
Excel Data import to program
//First look at how to get Excel data

// Get the data in the table
public System.Data.DataTable LoadExcel(string pPath)
{

        string connString = "Driver={Driver do Microsoft Excel(*.xls)};DriverId=790;SafeTransactions=0;ReadOnly=1;MaxScanRows=16;Threads=3;MaxBufferSize=2024;UserCommitSync=Yes;FIL=excel 8.0;PageTimeout=5;";  //Connection string  

        //Simply explain this continuous string, Driver={Driver do Microsoft Excel(*.xls)} This connection does not need to create a data source DSN, DRIVERID represents the driver ID, Excel 2003 after the use of 790,

        //FIL denotes Excel file type, Excel 2007 uses excel 8.0, MaxBufferSize denotes cache size. If your file is version 2010, you may report errors, so find the appropriate version of the parameter settings.

        connString += "DBQ=" + pPath; //DBQ represents the file name (full path) for reading Excel
        OdbcConnection conn = new OdbcConnection(connString);
        OdbcCommand cmd = new OdbcCommand();
        cmd.Connection = conn;
        //Get the first Sheet name in Excel as the table name at query time
        string sheetName = this.GetExcelSheetName(pPath);
        string sql = "select * from [" + sheetName.Replace('.', '#') + "$]";
        cmd.CommandText = sql;
        OdbcDataAdapter da = new OdbcDataAdapter(cmd);
        DataSet ds = new DataSet();
        try
        {
            da.Fill(ds);
            return ds.Tables[0];    //Return the contents of Excel data and save them in DataTable
        }
        catch (Exception x)
        {
            ds = null;
            throw new Exception("from Excel An error occurred while retrieving data from the file! May be Excel Version issues, you can consider reducing versions or modifying connection string values");
        }
        finally
        {
            cmd.Dispose();
            cmd = null;
            da.Dispose();
            da = null;
            if (conn.State == ConnectionState.Open)
            {
                conn.Close();
            }
            conn = null;
        }
    }

    // Get the name of the worksheet
    private string GetExcelSheetName(string pPath)
    {
        //Open an Excel application
        Microsoft.Office.Interop.Excel.Application excelApp;
        Workbook excelWB;//Create a workbook (WorkBook: Excel file body itself)
        Workbooks excelWBs;
        Worksheet excelWS;//Create a worksheet (that is, a subsheet in Excel)

        Sheets excelSts;

        excelApp = new Microsoft.Office.Interop.Excel.Application();
        if (excelApp == null)
        {
            throw new Exception("open Excel Error in application!");
        }
        excelWBs = excelApp.Workbooks;
        //Open an existing Workbook
        excelWB = excelWBs.Add(pPath);
        excelSts = excelWB.Sheets;
        //Select the first Sheet page
        excelWS = excelSts.get_Item(1);
        string sheetName = excelWS.Name;

        ReleaseCOM(excelWS);
        ReleaseCOM(excelSts);
        ReleaseCOM(excelWB);
        ReleaseCOM(excelWBs);
        excelApp.Quit();
        ReleaseCOM(excelApp);
        return sheetName;
    }

    // Release resources
    private void ReleaseCOM(object pObj)
    {
        try
        {
            System.Runtime.InteropServices.Marshal.ReleaseComObject(pObj);
        }
        catch
        {
            throw new Exception("Error releasing resources!");
        }
        finally
        {
            pObj = null;
        }
    }
We've got the data, and then we can get the data directly in our application by just passing the path of the file.

private void btnImport_Click(object sender, RoutedEventArgs e)
{
System.Data.DataTable dt = LoadExcel("D: sanjiawan"); // Data obtained by path

        //At this point, we can use this data to process, such as binding to the control that displays the data.
        MessageBox.Show("Successful import");
    }

"`
By acquiring Excel data, we can find that its operation mechanism is almost the same as that of database operation mechanism. We can think of Excel as a database to operate on.
Whether importing or exporting, we have seen the operation of releasing resources. This allows timely process optimization without affecting the performance of the program.
I hope it will be helpful to you all.

Topics: Excel SQL Database