0

我正在将数据从 datagridview 导出到 excel 表。数据由数字和字符组成。数字显示在单元格的最右侧,左侧的字符。我缺少一些数字格式。我希望数字也显示在单元格的另一侧。下面是导出到 excel 代码。

 private void button3_Click(object sender, EventArgs e)
    {
        Excel.Application xlApp;
        Excel.Workbook xlWorkBook;
        Excel.Worksheet xlWorkSheet;
      Excel.Range oRange;

        object misValue = System.Reflection.Missing.Value;

        xlApp = new Excel.Application();
        xlWorkBook = xlApp.Workbooks.Add(misValue);
        xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
        Excel.Range aRangeSingle = xlWorkSheet.get_Range("A1", "A1");
        aRangeSingle.ColumnWidth = 37;

        Excel.Range aRangeSingle2 = xlWorkSheet.get_Range("B1", "B1");
        aRangeSingle2.ColumnWidth = 65;



        int i = 0;
        int j = 0;
        try
        {

            for (i = 0; i <= dataGridView2.RowCount - 1; i++)
            {
                for (j = 0; j <= dataGridView2.ColumnCount - 1; j++)
                {
                    DataGridViewCell cell = dataGridView2[j, i];
                    xlWorkSheet.Cells[i + 1, j + 1] = cell.Value;//this has numbers also


                }
            }

        }
        catch (Exception)
        {
            MessageBox.Show("server not available while export to excel");
        } 
4

1 回答 1

0

将您的行更改为:

xlWorkSheet.Cells[i + 1, j + 1] = "'" + cell.Value;

如果 excel 在开头看到一个单引号,它会将其假定为 TEXT。但是在这种情况下,计算不会作为数字起作用。如果要用作数字,请将单元格向左对齐

于 2013-04-26T07:11:26.600 回答