强制excel使用C#将数据从SQL Server保存为文本数据类型

时间:2013-03-20 03:06:52

标签: c# sql excel types

将数据从SQL保存到Excel时出现问题。我为我的网络应用程序C#使用了。我将数据存储在SQL中作为nvarchar数据类型。

问题是当我将数据保存到Excel时,Excel会自动将“。0”数据转换为“0.00”。我想将数据保存到Excel中,就像在SQL中一样。我该怎么办?这是我用过的代码:

var excelApp = new Excel.Application();
    excelApp.Visible = true;
    Excel.Workbook workbook = excelApp.Workbooks.Add();
    Excel._Worksheet worksheet = (Excel._Worksheet)excelApp.ActiveSheet;


    worksheet.Cells[1, "A"] = "MJERA1";
    worksheet.Cells[1, "B"] = "MJERA2";
    worksheet.Cells[1, "C"] = "MJERA3";
    worksheet.Cells[1, "D"] = "MUSTERIJA";

    worksheet.Range["A1:D1", Type.Missing].Borders[Excel.XlBordersIndex.xlEdgeBottom].Color = System.Drawing.Color.Black;
    worksheet.Range["A1:D1", Type.Missing].Font.Bold = true;


    var must = new Must();
    var customerList = must.Ramiz_Musterija_ListByDate(Convert.ToDateTime(ddlTruckDate.SelectedItem.Value), int.Parse(ddlTruckNumber.SelectedItem.Value));

    var row = 1;
    foreach (var queryMust in customerList)
    {
        row++;
        worksheet.Cells[row, "A"] = queryMust.Mjera1;
        worksheet.Cells[row, "B"] = queryMust.Mjera2;
        worksheet.Cells[row, "C"] = queryMust.Mjera3;
        worksheet.Cells[row, "D"] = queryMust.Ime;
        // worksheet.Cells[row, "E"] = queryMust.MusterijaID;
    }

    var customerFindLastList = must.Ramiz_Musterija_FindLast(Convert.ToDateTime(ddlTruckDate.SelectedItem.Value), int.Parse(ddlTruckNumber.SelectedItem.Value));
    var customerRowNumList = must.Ramiz_Musterija_RowNum(Convert.ToDateTime(ddlTruckDate.SelectedItem.Value), int.Parse(ddlTruckNumber.SelectedItem.Value));

    var rowNumList = from f in customerFindLastList
                     join r in customerRowNumList
                     on f.MusterijaID equals r.MusterijaID
                     select new { r.RowNum };
    foreach (var rowItem in rowNumList)
    {
        worksheet.Range[string.Concat("A", (rowItem.RowNum + 1).ToString(), ":", "D", (rowItem.RowNum + 1).ToString()), Type.Missing].Borders[Excel.XlBordersIndex.xlEdgeBottom].Color = System.Drawing.Color.Black;
    }


    var autoFit = worksheet.Columns.AutoFit();

    workbook.SaveAs("MJERE " + ddlTruckDate.SelectedItem.Value, Excel.XlFileFormat.xlWorkbookNormal, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Excel.XlSaveAsAccessMode.xlExclusive, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
    ReleaseObject(excelApp);
    ReleaseObject(workbook);
    ReleaseObject(worksheet);

1 个答案:

答案 0 :(得分:0)

您需要获取变量的正确datatape,然后将相同的格式应用于单元格。查看文档。

Sheet.Cells[x, y].NumberFormat = "m/d/yyyy";