如何使用.NET更改XLS列DataType

时间:2012-03-29 03:46:39

标签: c# excel oledb xls excel-interop

我正在尝试将数据表导出到xls文件中。以下是我的代码:

using ExcelIt = Microsoft.Office.Interop.Excel;

protected void Export2xlsWorkBook(string filename)
        {
            if (filename != string.Empty)
            {
                if (filename.EndsWith(".xls"))
                    filename = txtNewFileName.Text + ".xls";
            }
            else
                filename = "NewFile.xls";

            filename = "C:\\Documents and Settings\\My Documents\\Exported XLS\\" + filename;

            ExcelIt.Application objXL = new ExcelIt.Application();
            ExcelIt.Workbook oWB;
            ExcelIt.Worksheet oSheet;
            ExcelIt.Range oRange;

            objXL.Visible = true;
            objXL.DisplayAlerts = false;

            oWB = objXL.Workbooks.Add(Missing.Value);

            DataTable dt = CreateDataTable();

            oSheet = (ExcelIt.Worksheet)oWB.ActiveSheet;
            oSheet.Name = "Exported Table";

            int rowCount = 1;
            foreach (DataRow dr in dt.Rows)
            {
                rowCount += 1;
                for (int i = 1; i < dt.Columns.Count + 1; i++)
                {
                    if (rowCount == 2)
                    {
                        oSheet.Cells[1, i] = dt.Columns[i - 1].ColumnName;
                    }
                    oSheet.Cells[rowCount, i] = dr[i - 1].ToString();
                }
            }

            oRange = oSheet.get_Range(oSheet.Cells[1, 1],
                          oSheet.Cells[rowCount, dt.Columns.Count]);

            oRange.EntireColumn.AutoFit();

            oRange = oSheet.get_Range(oSheet.Cells[1, 2], oSheet.Cells[rowCount + 10, dt.Columns.Count]);

            oSheet.Protection.AllowEditRanges.Add("NonePK", oRange, Missing.Value);

            oRange = oSheet.get_Range(oSheet.Cells[rowCount + 1, 1], oSheet.Cells[rowCount + 10, 1]);

            oSheet.Protection.AllowEditRanges.Add("PKEmptyRow", oRange, Missing.Value);

            oSheet._Protect(Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);

            oSheet = null;
            oRange = null;

            oWB.SaveAs(filename, ExcelIt.XlFileFormat.xlWorkbookNormal,
                Missing.Value, Missing.Value, Missing.Value, Missing.Value,
                ExcelIt.XlSaveAsAccessMode.xlExclusive,
                Missing.Value, Missing.Value, Missing.Value,
                Missing.Value, Missing.Value);

            oWB.Close(Missing.Value, Missing.Value, Missing.Value);
            oWB = null;
            objXL.Quit();

            GC.WaitForPendingFinalizers();
            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();
        }

出于某些原因,我想: 将所有列数据类型设置为文本。 目前我没有指定任何数据类型被设置为“general”而是。

有人可以告诉我如何实现这个目标吗? 此致

1 个答案:

答案 0 :(得分:2)

您可以使用Range.NumberFormat Property

Range usedRange = oSheet.UsedRange;
usedRange.NumberFormat = "@";