program story

Excel CSV-숫자 셀 형식

inputbox 2020. 9. 21. 07:40
반응형

Excel CSV-숫자 셀 형식


보고서를 CSV 파일로 생성합니다. Excel에서 파일을 열려고하면 셀의 내용을 기반으로 데이터 유형에 대한 가정을하고 그에 따라 형식을 다시 지정합니다.

예를 들어 CSV 파일에

...,005,...

그러면 Excel에서 5로 표시됩니다. 이것을 재정의하고 005를 표시하는 방법이 있습니까?

사용자가 CSV 파일을 두 번 클릭하여 열 수 있도록 파일 자체에 무언가를 수행하고 싶습니다.

Excel 2003을 사용합니다.


.csv 파일을 열 때 Excel이 적용되는 서식을 제어하는 ​​쉬운 방법은 없습니다. 그러나 다음은 도움이 될 수있는 세 가지 접근 방식입니다.

내 선호는 첫 번째 옵션입니다.

옵션 1 – 파일의 데이터 변경

.csv 파일의 데이터를 다음과 같이 변경할 수 있습니다. ..., =”005” , ... Excel에서 ..., 005 , ... 로 표시됩니다 .

Excel은 데이터를 수식으로 유지하지만 열을 복사하고 특수 값을 붙여 넣으면 수식이 제거되지만 서식은 유지됩니다.

옵션 2 – 데이터 서식 지정

단순히 형식 문제이고 해당 열의 모든 데이터 길이가 3 자리 인 경우. 그런 다음 Excel에서 데이터를 연 다음이 사용자 지정 형식 000 으로 데이터가 포함 된 열의 서식을 지정합니다.

옵션 3 – 파일 확장자를 .dif (데이터 교환 형식)로 변경

파일 확장자를 변경하고 파일 가져 오기 마법사를 사용하여 형식을 제어하십시오. 확장자가 .dif 인 파일을 더블 클릭하면 Excel에서 자동으로 열립니다.

단계별 :

  • 파일 확장자를 .csv 에서 .dif로 변경하십시오.
  • 파일을 두 번 클릭하여 Excel에서 엽니 다.
  • '파일 가져 오기 마법사'가 시작됩니다.
  • '파일 형식'을 '구분'으로 설정하고 '다음'버튼을 클릭합니다.
  • 구분자에서 '쉼표'를 선택하고 '다음'버튼을 클릭합니다.
  • 표시되는 데이터의 각 열을 클릭하고 '열 데이터 형식'을 선택하십시오. 값이 '005'인 열은 '텍스트'형식이어야합니다.
  • 완료 버튼을 클릭하면 지정한 형식으로 Excel에서 파일이 열립니다.

CSV를 사용하지 말고 SYLK를 사용하십시오.
http://en.wikipedia.org/wiki/SYmbolic_LinK_(SYLK)

서식을 훨씬 더 세부적으로 제어 할 수 있으며 Excel은 내용을 검사하여 필드 유형을 추측하지 않습니다. 약간 복잡해 보이지만 아주 작은 하위 집합을 사용하여 벗어날 수 있습니다.


이것은 Microsoft Office 2010, Excel 버전 14에서 작동합니다.

나는 "파일 자체에 뭔가를하는 것"이라는 OP의 선호를 잘못 읽었다. 가져 오기를 직접 형식화하는 솔루션을 원하는 사람들을 위해 여전히 이것을 유지하고 있습니다.

  1. 빈 (새) 파일 열기 (파일-> 통합 문서에서 새로 만들기)
  2. 가져 오기 마법사 열기 (데이터-> 텍스트에서)
  3. .csv 파일을 선택하고 가져 오기
  4. 대화 상자에서 '구분'을 선택하고 다음을 클릭합니다.
  5. 구분 기호를 선택하고 ( '쉼표'를 제외한 모든 항목 선택 취소) 텍스트 한정자를 선택한 후 (예 : {None}) 다음을 클릭합니다.
  6. 에서 데이터 미리보기 필드 텍스트로 원하는 열을 선택합니다. 강조되어야합니다.
  7. 에서 열 데이터 형식의 필드, '텍스트'를 선택합니다.
  8. 완료를 클릭하십시오.

범위를 텍스트로 간단히 포맷 할 수 있습니다.

또한 여기 에 숫자 형식과이를 프로그래밍하는 방법에 대한 멋진 기사가 있습니다.


사실 저는 최소한 Office 2003부터는 Excel 스프레드 시트를 XML 파일로 저장할 수 있다는 것을 발견했습니다. 따라서 XML 파일을 생성 할 수 있으며 두 번 클릭하면 Excel에서 열립니다. SYLK와 동일한 수준의 제어를 제공하지만 XML 구문이 더 직관적입니다.


셀에 끊기지 않는 공백을 추가하면 도움이 될 수 있습니다. 예를 들면 :"firstvalue";"secondvalue";"005 ";"othervalue"

Excel에서 텍스트로 처리하고 공백이 표시되지 않도록합니다. Windows에서는 alt + 0160을 입력하여 중단없는 공백을 추가 할 수 있습니다. 자세한 정보는 여기를 참조하십시오 : http://en.wikipedia.org/wiki/Non-breaking_space

Excel 2010에서 시도했습니다.이 문제에 대한 적절한 해결책을 찾는 사람들에게 도움이되기를 바랍니다.


I had this issue when exporting CSV data from C# code, and resolved this by prepending the leading zero data with the tab character \t, so the data was interpreted as text rather than numeric in Excel (yet unlike prepending other characters, it wouldn't be seen).

I did like the ="001" approach, but this wouldn't allow exported CSV data to be re-imported again to my C# application without removing all this formatting from the import CSV file (instead I'll just trim the import data).


I believe when you import the file you can select the Column Type. Make it Text instead of Number. I don't have a copy in front of me at the moment to check though.


Load csv into oleDB and force all inferred datatypes to string

i asked the same question and then answerd it with code.

basically when the csv file is loaded the oledb driver makes assumptions, you can tell it what assumptions to make.

My code forces all datatypes to string though ... its very easy to change the schema. for my purposes i used an xslt to get ti the way i wanted - but i am parsing a wide variety of files.


I know this is an old question, but I have a solution that isn't listed here.

When you produce the csv add a space after the comma but before your value e.g. , 005,.

This worked to prevent auto date formatting in excel 2007 anyway .


The Text Import Wizard method does NOT work when the CSV file being imported has line breaks within a cell. This method handles this scenario(at least with tab delimited data):

  1. Create new Excel file
  2. Ctrl+A to select all cells
  3. In Number Format combobox, select Text
  4. Open tab delimited file in text editor
  5. Select all, copy and paste into Excel

This has been driving me crazy all day (since indeed you can't control the Excel column types before opening the CSV file), and this worked for me, using VB.NET and Excel Interop:

        'Convert .csv file to .txt file.
        FileName = ConvertToText(FileName)

        Dim ColumnTypes(,) As Integer = New Integer(,) {{1, xlTextFormat}, _
                                                        {2, xlTextFormat}, _
                                                        {3, xlGeneralFormat}, _
                                                        {4, xlGeneralFormat}, _
                                                        {5, xlGeneralFormat}, _
                                                        {6, xlGeneralFormat}}

        'We are using OpenText() in order to specify the column types.
        mxlApp.Workbooks.OpenText(FileName, , , Excel.XlTextParsingType.xlDelimited, , , True, , True, , , , ColumnTypes)
        mxlWorkBook = mxlApp.ActiveWorkbook
        mxlWorkSheet = CType(mxlApp.ActiveSheet, Excel.Worksheet)


Private Function ConvertToText(ByVal FileName As String) As String
    'Convert the .csv file to a .txt file.
    'If the file is a text file, we can specify the column types.
    'Otherwise, the Codes are first converted to numbers, which loses trailing zeros.

    Try
        Dim MyReader As New StreamReader(FileName)
        Dim NewFileName As String = FileName.Replace(".CSV", ".TXT")
        Dim MyWriter As New StreamWriter(NewFileName, False)
        Dim strLine As String

        Do While Not MyReader.EndOfStream
            strLine = MyReader.ReadLine
            MyWriter.WriteLine(strLine)
        Loop

        MyReader.Close()
        MyReader.Dispose()
        MyWriter.Close()
        MyWriter.Dispose()

        Return NewFileName
    Catch ex As Exception
        MsgBox(ex.Message)
        Return ""
    End Try

End Function

When opening a CSV, you get the text import wizard. At the last step of the wizard, you should be able to import the specific column as text, thereby retaining the '00' prefix. After that you can then format the cell any way that you want.

I tried with with Excel 2007 and it appeared to work.


Well, excel never pops up the wizard for CSV files. If you rename it to .txt, you'll see the wizard when you do a File>Open in Excel the next time.


Put a single quote before the field. Excel will treat it as text, even if it looks like a number.

...,`005,...

EDIT: This is wrong. The apostrophe trick only works when entering data directly into Excel. When you use it in a CSV file, the apostrophe appears in the field, which you don't want.

http://support.microsoft.com/kb/214233


Just add ' before the number in the CSV doc.

참고URL : https://stackoverflow.com/questions/137359/excel-csv-number-cell-format

반응형