1

当我将联系人导出到 csv 文件时,进入我的项目会自动将手机号码格式以 91 开头转换为科学格式。

例如移动没有到导出数据

919433454320

科学格式时手机不转成csv文件

9.194E+11

将单元格格式化为小数点后 0 位的数字

919430000000

使用 Microsoft.Office.Interop.Excel.Application 将联系人导出到我的项目中

这里的工作簿是我的代码

  Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
            app.Visible = false;
            Workbook wb = app.Workbooks.Add();
            Worksheet ws = (Worksheet)wb.Worksheets.get_Item(1);
            object[,] rawData = new object[DataTable.Rows.Count + 1, DataTable.Columns.Count];

            for (int col = 0; col < DataTable.Columns.Count; col++)
            {
                rawData[0, col] = DataTable.Columns[col].ColumnName;
            }

            for (int col = 0; col < DataTable.Columns.Count; col++)
            {
                for (int row = 0; row < DataTable.Rows.Count; row++)
                {
                    rawData[row + 1, col] = DataTable.Rows[row].ItemArray[col];
                }
            }
            string[] callchar = new string[]  {"range of my excel sheet (e.g from a to Bz"};
            string excelRange = callchar[0] + "1:" + callchar[DataTable.Columns.Count - 1] + (DataTable.Rows.Count + 1).ToString();
            Range r = ws.Cells.EntireColumn.NumberFormat;
            ws.get_Range(excelRange, Type.Missing).Value2 = rawData;
            wb.SaveAs(Filename: FilePath, FileFormat: XlFileFormat.xlCSVWindows, ReadOnlyRecommended: false);
            wb.Close();
            app.Quit();
4

1 回答 1

0

您可以使用后期绑定来导出数据:

            // try to open excel
            Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");
            Type typeExcelApplication = Type.GetTypeFromProgID("Excel.Application");
            if (typeExcelApplication == null)
                throw new Exception("Excel is not installed (Excel.Application is not found)");
            object objExcelApplication = Activator.CreateInstance(typeExcelApplication);
            object objWorkBooks = objExcelApplication.GetType().InvokeMember("Workbooks", BindingFlags.GetProperty, null, objExcelApplication, null);
            object objWorkBook = objWorkBooks.GetType().InvokeMember("Add", BindingFlags.InvokeMethod, null, objWorkBooks, null);
            object objWorkSheet = objWorkBook.GetType().InvokeMember("ActiveSheet", BindingFlags.GetProperty, null, objWorkBook, null);

            // fill data (put object obj into cell [1,1])
            objWorkSheet.GetType().InvokeMember("Cells", BindingFlags.SetProperty, null, objWorkSheet, new object[] { 1, 1, obj});

            // display excel
            typeExcelApplication.InvokeMember("Visible", BindingFlags.SetProperty, null, objExcelApplication, new object[] { true });
            Marshal.ReleaseComObject(objExcelApplication);

Excel 应该正确处理类型,因此如果您提供obj-string它不会尝试从中生成数字(科学?)。

于 2013-02-22T13:35:07.507 回答