English 中文(简体)
采用宏观或全球大气分辨率将一些科学分辨率转换成数字格式
原标题:Convert a number in scientific notation to numeric format in Excel using a macro or VBA
  • 时间:2012-04-09 14:18:36
  •  标签:
  • excel
  • vba

MS Excel吃了我的头盔。 它是随机将数字转换为科学脱硫格式。 当我把以表格形式保存的档案装入服务器时,就会造成问题。 我知道,我可以提供格式文件,并且确实有很多ancy。 但我要说的是,我可以.。

是否存在着一种对所有囚室的循环,如果囚室中的数量是科学的排位,那么它会将其转换成数字形式?

Say:

Input: spaces signify different cells.
1.00E13 egalitarian 

宏观后产出:

10000000000000 egalitarian

我在2007年在Excel试图这样做。

最佳回答

我写了解决这一问题的简单C#方案。 希望得到使用。

Input:

档案存放的投稿(假设档案为txt格式)。

Output:

转换档案的目录将公布。

Delimiter:

Column delimiter.

The code

using System;
using System.Text.RegularExpressions;
using System.IO;
using System.Text;
using System.Threading;

namespace ConvertToNumber
{
    class Program
    {
        private static string ToLongString(double input)
        {
            string str = input.ToString().ToUpper();

            // If string representation was collapsed from scientific notation, just return it:
            if (!str.Contains("E")) 
                return str;

            var positive = true;
            if (input < 0)
            {
                positive = false;
            }

            string sep = Thread.CurrentThread.CurrentCulture.NumberFormat.NumberDecimalSeparator;
            char decSeparator = sep.ToCharArray()[0];

            string[] exponentParts = str.Split( E );
            string[] decimalParts = exponentParts[0].Split(decSeparator);

            // Fix missing decimal point:
            if (decimalParts.Length == 1) 
                decimalParts = new string[] { exponentParts[0], "0" };

            int exponentValue = int.Parse(exponentParts[1]);

            string newNumber = decimalParts[0].Replace("-","").
                Replace("+","") + decimalParts[1];

            string result;

            if (exponentValue > 0)
            {
                if(positive)
                    result =
                       newNumber +
                       GetZeros(exponentValue - decimalParts[1].Length);
                else
                    result = "-"+
                     newNumber +
                     GetZeros(exponentValue - decimalParts[1].Length);


            }
            else // Negative exponent
            {
                if(positive)
                    result =
                        "0" +
                        decSeparator +
                        GetZeros(exponentValue + decimalParts[0].Replace("-", "").
                                   Replace("+", "").Length) + newNumber;
                else
                    result =
                    "-0" +
                    decSeparator +
                    GetZeros(exponentValue + decimalParts[0].Replace("-", "").
                             Replace("+", "").Length) + newNumber;

                result = result.TrimEnd( 0 );
            }
            float temp = 0.00F;

            if (float.TryParse(result, out temp))
            {
                return result;
            }
            throw new  Exception();
        }

        private static string GetZeros(int zeroCount)
        {
            if (zeroCount < 0)
                zeroCount = Math.Abs(zeroCount);

            StringBuilder sb = new StringBuilder();

            for (int i = 0; i < zeroCount; i++) sb.Append("0");

            return sb.ToString();
        }

        static void Main(string[] args)
        {
            //Get Input Directory.
            Console.WriteLine(@"Enter the Input Directory");
            var readLine = Console.ReadLine();
            if (readLine == null)
            {
                Console.WriteLine(@"Enter the input path properly.");
                return;
            }
            var pathToInputDirectory = readLine.Trim();

            //Get Output Directory.
            Console.WriteLine(@"Enter the Output Directory");
            readLine = Console.ReadLine();
            if (readLine == null)
            {
                Console.WriteLine(@"Enter the output path properly.");
                return;
            }
            var pathToOutputDirectory = readLine.Trim();

            //Get Delimiter.
            Console.WriteLine("Enter the delimiter;");
            var columnDelimiter = (char) Console.Read();

            //Loop over all files in the directory.
            foreach (var inputFileName in Directory.GetFiles(pathToInputDirectory))
            {
                var outputFileWithouthNumbersInScientificNotation = string.Empty;
                Console.WriteLine("Started operation on File : " + inputFileName);

                if (File.Exists(inputFileName))
                {
                    // Read the file
                    using (var file = new StreamReader(inputFileName))
                    {
                        string line;
                        while ((line = file.ReadLine()) != null)
                        {
                            String[] columns = line.Split(columnDelimiter);
                            var duplicateLine = string.Empty;
                            int lengthOfColumns = columns.Length;
                            int counter = 1;
                            foreach (var column in columns)
                            {
                                var columnDuplicate = column;
                                try
                                {
                                    if (Regex.IsMatch(columnDuplicate.Trim(),
                                                      @"^[+-]?[0-9]+(.[0-9]+)?[E]([+-]?[0-9]+)$",
                                                      RegexOptions.IgnoreCase))
                                    {
                                        Console.WriteLine("Regular expression matched for this :" + column);

                                        columnDuplicate = ToLongString(Double.Parse
                                                                           (column,
                                                                            System.Globalization.NumberStyles.Float));

                                        Console.WriteLine("Converted this no in scientific notation " +
                                                          "" + column + "  to this number " +
                                                          columnDuplicate);
                                    }
                                }
                                catch (Exception)
                                {

                                }
                                duplicateLine = duplicateLine + columnDuplicate;

                                if (counter != lengthOfColumns)
                                {
                                    duplicateLine = duplicateLine + columnDelimiter.ToString();
                                }
                                counter++;
                            }
                            duplicateLine = duplicateLine + Environment.NewLine;
                            outputFileWithouthNumbersInScientificNotation = outputFileWithouthNumbersInScientificNotation + duplicateLine;
                        }

                        file.Close();
                    }

                    var outputFilePathWithoutNumbersInScientificNotation
                        = Path.Combine(pathToOutputDirectory, Path.GetFileName(inputFileName));

                    //Create the directory if it does not exist.
                    if (!Directory.Exists(pathToOutputDirectory))
                        Directory.CreateDirectory(pathToOutputDirectory);

                    using (var outputFile =
                        new StreamWriter(outputFilePathWithoutNumbersInScientificNotation))
                    {
                        outputFile.Write(outputFileWithouthNumbersInScientificNotation);
                        outputFile.Close();
                    }

                    Console.WriteLine("The transformed file is here :" +
                        outputFilePathWithoutNumbersInScientificNotation);
                }
            }
        }
    }
}

在我们无法在MS Excel上公开的大量档案的情况下,这项工作做得很好。

问题回答

Thanks Peter. I updated your original work to: 1) take in an input file or path 2) only write out a processing statement after every 1000 lines read 3) write the transformed lines to the output file as they are processed so a potentially large string is not kept hanging around 4) added a readkey at the end so that console does not exit automatically while debuggging

    using System;
using System.Text.RegularExpressions;
using System.IO;
using System.Text;
using System.Threading;

namespace ConvertScientificToLong
{
    class Program
    {
        private static string ToLongString(double input)
        {
            string str = input.ToString().ToUpper();

            // If string representation was collapsed from scientific notation, just return it:
            if (!str.Contains("E"))
                return str;

            var positive = true;
            if (input < 0)
            {
                positive = false;
            }

            string sep = Thread.CurrentThread.CurrentCulture.NumberFormat.NumberDecimalSeparator;
            char decSeparator = sep.ToCharArray()[0];

            string[] exponentParts = str.Split( E );
            string[] decimalParts = exponentParts[0].Split(decSeparator);

            // Fix missing decimal point:
            if (decimalParts.Length == 1)
                decimalParts = new string[] { exponentParts[0], "0" };

            int exponentValue = int.Parse(exponentParts[1]);

            string newNumber = decimalParts[0].Replace("-", "").
                Replace("+", "") + decimalParts[1];

            string result;

            if (exponentValue > 0)
            {
                if (positive)
                    result =
                       newNumber +
                       GetZeros(exponentValue - decimalParts[1].Length);
                else
                    result = "-" +
                     newNumber +
                     GetZeros(exponentValue - decimalParts[1].Length);


            }
            else // Negative exponent
            {
                if (positive)
                    result =
                        "0" +
                        decSeparator +
                        GetZeros(exponentValue + decimalParts[0].Replace("-", "").
                                   Replace("+", "").Length) + newNumber;
                else
                    result =
                    "-0" +
                    decSeparator +
                    GetZeros(exponentValue + decimalParts[0].Replace("-", "").
                             Replace("+", "").Length) + newNumber;

                result = result.TrimEnd( 0 );
            }
            float temp = 0.00F;

            if (float.TryParse(result, out temp))
            {
                return result;
            }
            throw new Exception();
        }

        private static string GetZeros(int zeroCount)
        {
            if (zeroCount < 0)
                zeroCount = Math.Abs(zeroCount);

            StringBuilder sb = new StringBuilder();

            for (int i = 0; i < zeroCount; i++) sb.Append("0");

            return sb.ToString();
        }

        static void Main(string[] args)
        {
            //Get Input Directory.
            Console.WriteLine(@"Enter the Input Directory or File Path");
            var readLine = Console.ReadLine();
            if (readLine == null)
            {
                Console.WriteLine(@"Enter the input path properly.");
                return;
            }
            var pathToInputDirectory = readLine.Trim();

            //Get Output Directory.
            Console.WriteLine(@"Enter the Output Directory");
            readLine = Console.ReadLine();
            if (readLine == null)
            {
                Console.WriteLine(@"Enter the output path properly.");
                return;
            }
            var pathToOutputDirectory = readLine.Trim();

            //Get Delimiter.
            Console.WriteLine("Enter the delimiter;");
            var columnDelimiter = (char)Console.Read();

            string[] inputFiles = null;

            if (File.Exists(pathToInputDirectory))
            {
                inputFiles = new String[]{pathToInputDirectory};
            }
            else
            {
                inputFiles = Directory.GetFiles(pathToInputDirectory);
            }

            //Loop over all files in the directory.
            foreach (var inputFileName in inputFiles)
            {
                var outputFileWithouthNumbersInScientificNotation = string.Empty;
                Console.WriteLine("Started operation on File : " + inputFileName);

                if (File.Exists(inputFileName))
                {
                    string outputFilePathWithoutNumbersInScientificNotation
                        = Path.Combine(pathToOutputDirectory, Path.GetFileName(inputFileName));

                    //Create the directory if it does not exist.
                    if (!Directory.Exists(pathToOutputDirectory))
                        Directory.CreateDirectory(pathToOutputDirectory);

                    using (var outputFile =
                        new StreamWriter(outputFilePathWithoutNumbersInScientificNotation))
                    {
                        // Read the file
                        using (StreamReader file = new StreamReader(inputFileName))
                        {
                            string line;
                            int lineCount = 0;
                            while ((line = file.ReadLine()) != null)
                            {
                                String[] columns = line.Split(columnDelimiter);
                                var duplicateLine = string.Empty;
                                int lengthOfColumns = columns.Length;
                                int counter = 1;
                                foreach (var column in columns)
                                {
                                    var columnDuplicate = column;
                                    try
                                    {
                                        if (Regex.IsMatch(columnDuplicate.Trim(),
                                                          @"^[+-]?[0-9]+(.[0-9]+)?[E]([+-]?[0-9]+)$",
                                                          RegexOptions.IgnoreCase))
                                        {
                                            //Console.WriteLine("Regular expression matched for this :" + column);

                                            columnDuplicate = ToLongString(Double.Parse
                                                                               (column,
                                                                                System.Globalization.NumberStyles.Float));

                                            //Console.WriteLine("Converted this no in scientific notation " +
                                            //                  "" + column + "  to this number " +
                                            //                  columnDuplicate);

                                            if (lineCount % 1000 == 0)
                                            {
                                                Console.WriteLine(string.Format("processed {0} lines. still going....", lineCount));
                                            }
                                        }
                                    }
                                    catch (Exception)
                                    {

                                    }
                                    duplicateLine = duplicateLine + columnDuplicate;

                                    if (counter != lengthOfColumns)
                                    {
                                        duplicateLine = duplicateLine + columnDelimiter.ToString();
                                    }
                                    counter++;
                                }

                                outputFile.WriteLine(duplicateLine);

                                lineCount++;
                            }
                        }
                    }
                    Console.WriteLine("The transformed file is here :" +
                        outputFilePathWithoutNumbersInScientificNotation);

                    Console.WriteLine(@"Hit any key to exit");
                    Console.ReadKey();
                }
            }
        }
    }
}

一种比较容易的方法是将其保存成一个文件。 然后,你不要仅仅打开档案,而是去上数据表,选择“从文字上”来,以便你能够找到对话箱。 这样,你就可以确定该栏中科学术语为案文,以删除该格式。 进口档案,然后,你可以对其进行改革,以编号或表示任何希望。





相关问题
import of excel in SQL imports NULL lines

I have a stored procedure that imports differently formatted workbooks into a database table, does work on them then drops the table. Here is the populating query. SELECT IDENTITY(INT,1,1) AS ID ...

Connecting to Oracle 10g with ODBC from Excel VBA

The following code works. the connection opens fine but recordset.recordCount always returns -1 when there is data in the table. ANd If I try to call any methods/properties on recordset it crashes ...

Excel date to Unix timestamp

Does anyone know how to convert an Excel date to a correct Unix timestamp?

C# GemBox Excel Import Error

I am trying to import an excel file into a data table using GemBox and I keep getting this error: Invalid data value when extracting to DataTable at SourceRowIndex: 1, and SourceColumnIndex: 1. As ...

Importing from excel "applications" using SSIS

I am looking for any tips or resources on importing from excel into a SQL database, but specifically when the information is NOT in column and row format. I am currently doing some pre-development ...

热门标签