导出到excel输出修改

时间:2011-02-20 20:23:27

标签: c# asp.net

我使用以下代码将数据集从c#导出到excel。我得到以下输出:

ABC | 1 | 2/15/2011 21:36 | Systems Analyst | Project Duration
ABC | 1 | 2/15/2011 21:36 | Systems Analyst | Skill of Team
ABC | 1 | 2/15/2011 21:36 | Systems Analyst | Process

然而,我想要做的是以下格式输出数据,并添加列标题。如果StoryCategoryID的输出为1,我想显示NEGATIVE,如果输出为0,我想显示为POSITIVE。请帮忙!

Story | Story Type | Date | Project Member | Tag 1 | Tag 2 | Tag 3

ABC | Negative | 2/15/2011 21:36 | Project Duration | Skill of Team | Process

代码:

protected void btnExcelExport_Click(object sender, EventArgs e)
{

        string sql = null;
        string data = null;
        //string path = save_as.Text;

        int i = 0;
        int j = 0;

        Excel.Application xlApp;
        Excel.Workbook xlWorkBook;
        Excel.Worksheet xlWorkSheet;
        object misValue = System.Reflection.Missing.Value;

        xlApp = new Excel.ApplicationClass();
        xlWorkBook = xlApp.Workbooks.Add(misValue);
        xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);

        //connectionString = "data source=servername;initial catalog=databasename;user id=username;password=password;";
        SqlConnection cnn = new SqlConnection(GetConnectionString());
        cnn.Open();
        sql = "SELECT s.Story, s.StoryCategoryID, s.CreationDate, m.CompanyRole, af.Name FROM Story s INNER JOIN ProjectIterationMember pm ON pm.ProjectIterationMemberID = s.ProjectIterationMemberID INNER JOIN Iterations i ON i.ProjectIterationID = pm.ProjectIterationID INNER JOIN Member m ON m.MemberID = pm.MemberID INNER JOIN ProjectStoryFactors psf ON psf.StoryID = s.StoryID INNER JOIN AgileFactors af ON af.AgileFactorID = psf.AgileFactorID WHERE i.ProjectID = '" + proj_id + "'";
        SqlDataAdapter dscmd = new SqlDataAdapter(sql, cnn);
        DataSet ds = new DataSet();
        dscmd.Fill(ds);

        for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
        {
            for (j = 0; j <= ds.Tables[0].Columns.Count - 1; j++)
            {
                data = ds.Tables[0].Rows[i].ItemArray[j].ToString();
                xlWorkSheet.Cells[i + 1, j + 1] = data;
            }
        }

        xlWorkBook.SaveAs("excelDocument" + DateTime.Now.Ticks + ".xls", Excel.XlFileFormat.xlWorkbookNormal, misValue, misValue, misValue, misValue, Excel.XlSaveAsAccessMode.xlExclusive, misValue, misValue, misValue, misValue, misValue);
        xlWorkBook.Close(true, misValue, misValue);
        xlApp.Quit();

        releaseObject(xlWorkSheet);
        releaseObject(xlWorkBook);
        releaseObject(xlApp);

        //MessageBox.Show("Excel file created , you can find the file c:\\csharp.net-informations.xls");
    }

1 个答案:

答案 0 :(得分:1)

首先,在性能方面,在Excel中写入范围然后逐个单元地写入要快得多。您可以通过从表中的数据创建二维数组并将其直接写入范围来完成此操作。

关于标题:只需在Excel的第一行中写下所需的文本即可。如果您愿意,甚至可以设置AutoFilter。在编写数据时,从第2行开始。

将值更改为“Positive”或“Negative”:在开始写入excel之前执行此操作。只需更改源中的值(如果您愿意,可以更改另一个数据表的数组)。

//Create 2-dimensional array with the data from the datatable
DataTable dt = ds.Tables[0];
string[,] arrValues = new string[dt.Rows.Count, dt.Columns.Count];

for (int i = 0; i < dt.Rows.Count; i++)
{
    for (int j = 0; j < dt.Columns.Count; j++)
    {
        arrValues[i, j] = dt.Rows[i].ItemArray[j].ToString();
    }
}

//Change the data from the column StoryCategoryID here
//Just loop through the items in the correct column of the array
//and check whether it's "0" or "1"

//Add headers
for (int i = 0; i < dt.Columns.Count; i++)
{
    xlWorkSheet.Cells[1, i + 1] = dt.Columns[i].ColumnName;
    //Or any name you like 
}

//Create range (start at row 2 because of header-row)
Range xlRange = (Range)xlWorkSheet.Cells[2, 1];
xlRange = xlRange.Resize[dt.Rows.Count, dt.Columns.Count];

//Fill range
xlRange.Value = arrValues;

//Format document
xlWorkSheet.EnableAutoFilter = true;
xlWorkSheet.Cells.AutoFilter(1);
xlWorkSheet.Range["A1", "A1"].EntireRow.Font.Bold = true;
xlWorkSheet.Columns.AutoFit();

我使用范围而不是逐个单元地传递值的原因是由于性能。对于大约1500条记录(15种颜色),创建一个Excel文件需要大约7或8分钟,当这样做时(使用范围)需要大约5或10秒。

(这是我已经转换出来的一些VB.Net代码,所以也许可能会有一些“misValue”,你必须传递其他参数,但我认为你得到的图片。)