UE4读取CSV文件
1、首先新建excle文件,在文件中列好相关内容。
2、点击另存为选择
点保存会弹出
选择 是 ,这样就会生成一份*.csv文件。
3、接下来在代码中读取该文件。
// 目前ue4中提供了FCsvParser类来方便读取csv文件
1 FString CSVBuffer; 2 FFileHelper::LoadFileToString(CSVBuffer, *FileName); 3 4 const FCsvParser CsvParser(CSVBuffer); 5 TArrayconst TCHAR*>> Content = CsvParser.GetRows(); 6 7 int32 Index = 0; 8 for (auto Value : Content) //TArray & 9 { 10 TArrayTemp; 11 for (const TCHAR*& Chr : Value) 12 { 13 Temp.Add(Chr); 14 //UE_LOG(LogBH, Warning, TEXT("LoadCSVFile = %s "), *Tem); 15 } 16 m_TableMap.Add(Temp); 17 }
//-----------------------------------------------------------------------------------------------------------------------------------------------
//-----------------------------------------------------------------------------------------------------------------------------------------------
以下是之前自己解析csv的代码
1 bool LoadCSVFromFile(FString FileName) 2 { 3 FString CSVFile = FPaths::ProjectConfigDir() + FileName; 4 5 FArchive* FileReader(IFileManager::Get().CreateFileReader(*CSVFile)); 6 if (FileReader == nullptr) 7 { 8 FPlatformMisc::LowLevelOutputDebugStringf(TEXT("LoadCSVFromFile %s Failed"), *FileName); 9 10 return false; 11 } 12 13 // 14 FileReader->Flush(); 15 int64 fileLength = FileReader->TotalSize(); 16 char *fileBuffer = new char[fileLength + 1]; 17 FileReader->Serialize(fileBuffer, fileLength); 18 fileBuffer[fileLength] = 0; 19 20 m_CSVBuffer = UTF8_TO_TCHAR(fileBuffer); 21 m_CSVHead = m_CSVBuffer.Left(3); 22 char *pBegin = fileBuffer/* +3*/; 23 char *pEnd = strchr(pBegin, '\n'); 24 25 // get column 26 FString StrColumn; 27 StrColumn.AppendChars(UTF8_TO_TCHAR(pBegin), pEnd - pBegin); 28 29 // parse string 30 m_ColumnMap.Empty(); 31 //m_TableMap.Empty(); 32 33 GetParamFromString(StrColumn, m_ColumnMap); 34 m_TableMap.Add(m_ColumnMap); 35 36 // get data 37 pBegin = pEnd + 1; 38 pEnd = strchr(pBegin, '\n'); 39 while (pEnd) 40 { 41 FString StrTemp; 42 StrTemp.AppendChars(UTF8_TO_TCHAR(pBegin), pEnd - pBegin); 43 TArrayStringVec; 44 GetParamFromString(StrTemp, StringVec); 45 if (m_ColumnMap.Num() != StringVec.Num()) { 46 FPlatformMisc::LowLevelOutputDebugStringf(TEXT("Load failed %s"), *FileName); 47 return false; 48 } 49 m_TableMap.Add(StringVec); 50 51 pBegin = pEnd + 1; 52 pEnd = strchr(pBegin, '\n'); 53 } 54 55 56 // Close file 57 delete[] fileBuffer; 58 fileBuffer = NULL; 59 60 pBegin = NULL; 61 pEnd = NULL; 62 63 //FileReader->Close(); 64 delete FileReader; 65 UE_LOG(LogHttpApi, Log, TEXT("LoadCSV(%s) Succeeded"), *FileName); 66 return true; 67 }
1 int32 UHttpApiComponent::GetParamFromString(FString ScrStr, TArray&OutBuffer, char delim) 2 { 3 char* Texts = TCHAR_TO_ANSI(*ScrStr); 4 int32 StrLen = ScrStr.Len(); 5 char Buffer[512]; 6 int index = 0; 7 for (int32 i = 0; i < StrLen; i++) 8 { 9 if (Texts[i] == delim || Texts[i] == '\r') 10 { 11 Buffer[index] = 0; 12 FString Tem = UTF8_TO_TCHAR(Buffer); 13 OutBuffer.Add(Tem); 14 index = 0; 15 } 16 else 17 Buffer[index++] = Texts[i]; 18 } 19 return OutBuffer.Num(); 20 }