将DataTable导出为ex​​cel NumberFormat百分比如何删除额外的十进制符号c#问题

时间:2017-10-19 12:58:10

标签: c# excel datagridview datatable

我正在将DataTable导出到Excel,其中一列是计算出的百分比。

我在DataGridView中显示表单中的数据,并格式化代码中的列,以所需格式显示百分比值,即.99450294将为99.45%。

在导出时我可以导出到Excel,同一列显示相同的值,但是如果结果值为100%,则显示为100%。%在百分号之前添加小数位。

如何删除与导出时100%值匹配的项目的小数点符号?

这是我的代码;

using System;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Windows.Forms;
using Excel = Microsoft.Office.Interop.Excel;

namespace CLStats
{
public partial class FrmMain : Form
{
    DataTable dt = new DataTable();

    public FrmMain()
    {
        InitializeComponent();
    }

    private void BtnRunReport_Click(object sender, EventArgs e)
    {
        Cursor.Current = Cursors.WaitCursor;

        int year = (int)NmUDYear.Value ;
        int month = CbMonth.SelectedIndex+1;
        SqlConnection conn = new SqlConnection(Globals.ConStatic);
        SqlDataAdapter dataAdapter = new SqlDataAdapter($"SELECT T1.CODELINE AS Codeline, T1.CODELINELIMITS AS Limits, T1.TYPE AS Type, sum(t1.CONTROLFAILCOUNT) as ControlFailCount, sum(t1.CONTROLSENTCOUNT) as CONTROLSENTCOUNT, sum(t1.INDICATIONCOUNT) as INDICATIONCOUNT, 1 - (sum(t1.CONTROLFAILCOUNT) / (sum(T1.CONTROLSENTCOUNT) * 1.0000)) as SUCCESSRATIO FROM (SELECT tmdsDatabaseStatistics.dbo.tblStatisticsCodeStationMonth.CODELINE, tmdsDatabaseStatic.dbo.tblCodelines.Legacytype as Type, tmdsDatabaseStatic.dbo.tblCodelines.CodeLineLimits, tmdsDatabaseStatistics.dbo.tblStatisticsCodeStationMonth.CONTROLFAILCOUNT, tmdsDatabaseStatistics.dbo.tblStatisticsCodeStationMonth.CONTROLSENTCOUNT, tmdsDatabaseStatistics.dbo.tblStatisticsCodeStationMonth.INDICATIONCOUNT FROM tmdsDatabaseStatistics.dbo.tblStatisticsCodeStationMonth INNER JOIN tmdsDatabaseStatic.dbo.tblCodeLines ON tmdsDatabaseStatistics.dbo.tblStatisticsCodeStationMonth.codeline = tmdsDatabaseStatic.dbo.tblCodeLines.CodelineNumber WHERE month = {month} AND codeline <> 415 AND year ={year} AND CONTROLSENTCOUNT <> 0) AS T1 GROUP BY T1.CODELINE , T1.TYPE, T1.CODELINELIMITS ORDER BY TYPE, CONTROLFAILCOUNT DESC, CODELINE DESC", Globals.ConStatic);
        conn.Open();
        dataAdapter.Fill(dt);
        conn.Close();
        Dg.DataSource = dt;
        Dg.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
        Dg.CellFormatting += new DataGridViewCellFormattingEventHandler(Dg_CellFormatting);

        Cursor.Current = Cursors.Default;
    }

    void Dg_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
    {
        if (e.ColumnIndex == 6 && e.RowIndex != Dg.NewRowIndex)
        {
            e.CellStyle.Format = "P2";
        }
    }

    private void BtnSaveReport_Click(object sender, EventArgs e)
    {
        Cursor.Current = Cursors.WaitCursor;
        Excel.Application xlApp;
        CultureInfo CurrentCI = Thread.CurrentThread.CurrentCulture;
        Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
        Excel.Workbook xlWorkBook;
        Excel.Worksheet xlWorkSheet;
        Excel.Range range;
        object misValue = Missing.Value;
        xlApp = new Excel.Application
        {
            DisplayAlerts = false
        };

        xlWorkBook = xlApp.Workbooks.Add(misValue);
        xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
        xlWorkSheet.Name = "Control Failures Report";

        for (var b = 0; b < dt.Columns.Count; b++)
        {
            xlWorkSheet.Cells[1, b + 1] = dt.Columns[b].ColumnName;
            range = xlWorkSheet.Cells[1, b + 1];
            range.Interior.ColorIndex = 15;
            range.Font.Bold = true;

            range[2, 7].EntireColumn.NumberFormat = "#.####%";

        }

        for (var r = 0; r < dt.Rows.Count; r++)
        {
            for (var a = 0; a < dt.Columns.Count; a++)
            {
                xlWorkSheet.Cells[r + 2, a + 1] = dt.Rows[r][a].ToString();
            }

        }

        Excel.Range columns = xlWorkSheet.UsedRange.Columns;
        columns.AutoFit();
        xlWorkSheet.Rows[1].Insert();
        Excel.Range newRow = xlWorkSheet.Rows[1];
        Excel.Range newCell = newRow.Cells[1];
        newCell.Value = DateTime.Now.ToString("dd/MM/yyyy");

        xlWorkBook.SaveAs("ControlFailuresAuto.xlsx",
            Excel.XlFileFormat.xlOpenXMLWorkbook, misValue, misValue, false, false,
            Excel.XlSaveAsAccessMode.xlNoChange,
            Excel.XlSaveConflictResolution.xlUserResolution, true
            , misValue, misValue, misValue);
        xlWorkBook.Close(true, misValue, misValue);
        xlApp.Quit();

        ReleaseObject(xlWorkSheet);
        ReleaseObject(xlWorkBook);
        ReleaseObject(xlApp);

        MessageBox.Show("Report created, you can find the file Documents\\ControlFailuresAuto.xlsx");
        Cursor.Current = Cursors.Default;
    }

    private void ReleaseObject(object obj)
    {
        try
        {
            System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
            obj = null;
        }
        catch (Exception ex)
        {
            obj = null;
            MessageBox.Show("Exception Occured while releasing object " + ex.ToString());
        }
        finally
        {
            GC.Collect();
        }
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        CbMonth.SelectedIndex = 0;
    }
}

由于

1 个答案:

答案 0 :(得分:1)

尝试将数字格式更改为#。00%如果您想要100%不带小数的条件且数字格式为#%