从列表中将标题读入Excel工作表

时间:2018-01-19 10:51:12

标签: c# database excel devexpress export-to-excel

我正在创建一个导出Excel工作表的程序,我想使用一个列表来读取标题(List<String> lFields),但由于某种原因它不起作用,DateTime虽然有效。

   using (Workbook workbook = new Workbook())
                {
                    Worksheet sht = workbook.Worksheets[0];
                    try
                    {
                        rowcount = 0;

                        //top headers
                        sht.Cells[rowcount, 1].Value = DBName;
                        int cols = lFields.Count() + 3;
                        sht.Cells[rowcount, cols].Value = Convert.ToString(DateTime.Now);

                        rowcount++;

                        //headers
                        for (int i = 0; i < lFields.Count(); i++)
                        {
                            sht.Cells[rowcount, i].Value = lfields[i];
                        }

                        //styling
                        sht.Rows[rowcount].Font.Name = "Calibri";
                        sht.Rows[rowcount].Font.Size = 10;
                        sht.Rows[rowcount].Font.Bold = true;
                        sht.Rows[rowcount].Font.Italic = false;
                        rowcount++;
                        sht.FreezeRows(0);

                        int RowCount = 0;

1 个答案:

答案 0 :(得分:0)

来自Microsfot支持:https://support.microsoft.com/en-us/help/306572/how-to-query-and-display-excel-data-by-using-asp-net--ado-net--and-vis

您可以将Excel文件作为sql表查询,然后恢复标题:

// Create connection string variable. Modify the "Data Source"
// parameter as appropriate for your environment.
String sConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + Server.MapPath("../ExcelData.xls") + ";" +
"Extended Properties=Excel 8.0;";

// Create connection object by using the preceding connection string.
OleDbConnection objConn = new OleDbConnection(sConnectionString);

// Open connection with the database.
objConn.Open();

// The code to follow uses a SQL SELECT command to display the data from the worksheet.

// Create new OleDbCommand to return data from worksheet.
OleDbCommand objCmdSelect =new OleDbCommand("SELECT * FROM myRange1", objConn);

// Create new OleDbDataAdapter that is used to build a DataSet
// based on the preceding SQL SELECT statement.
OleDbDataAdapter objAdapter1 = new OleDbDataAdapter();

// Pass the Select command to the adapter.
objAdapter1.SelectCommand = objCmdSelect;

// Create new DataSet to hold information from the worksheet.
DataSet objDataset1 = new DataSet();

// Fill the DataSet with the information from the worksheet.
objAdapter1.Fill(objDataset1, "XLData");

// Bind data to DataGrid control.
DataGrid1.DataSource = objDataset1.Tables[0].DefaultView;
DataGrid1.DataBind();

// Clean up objects.
objConn.Close();