UE4 C++ I can't get Json Nested Values to TArray - c++

I'm doing a GET Request to an online API but I can't get nested Json values to set to an array in C++ (Unreal Engine 4).
I got all values except nested array LE (key)
Here is JSON
{
"Id": 8,
"Nome": "Name",
"DataInicial": "2018-10-01T00:00:00",
"DataFinal": "2018-12-31T00:00:00",
"VL": 270174.982,
"CN": 461,
"Met": 354940,
"PM": 76.118493829943088972784132529,
"LE": [
{
"Id": 25,
"Nome": "Suco",
"Cor": "#510077",
"ValorNegociacaoGanha": 57772.452,
"CountNegociacaoGanha": 107,
"Meta": 66700,
"PercentualMeta": 86.61537031484257871064467766
},
{
"Id": 23,
"Nome": "Espumante",
"Cor": "#edd865",
"ValorNegociacaoGanha": 52494.03,
"CountNegociacaoGanha": 93,
"Meta": 66700,
"PercentualMeta": 78.701694152923538230884557721
}
]
}
Here is important code
void AHttpActor::OnResponseReceived(FHttpRequestPtr Request, FHttpResponsePtr Response, bool bWasSuccessful) {
//Create a pointer to hold the json serialized data
TSharedPtr<FJsonObject> JsonObject;
//Create a reader pointer to read the json data
TSharedRef<TJsonReader<>> Reader = TJsonReaderFactory<>::Create(Response->GetContentAsString());
//Deserialize the json data given Reader and the actual object to deserialize
if (FJsonSerializer::Deserialize(Reader, JsonObject)) {
//Get the value of the json object by field name
int32 id = JsonObject->GetIntegerField("Id");
FString nome = JsonObject->GetStringField("Nome");
FString DataInicial = JsonObject->GetStringField("DataInicial");
FString DataFinal = JsonObject->GetStringField("DataFinal");
double VN = JsonObject->GetNumberField("VN");
int32 CN = JsonObject->GetIntegerField("CN");
int32 Met = JsonObject->GetIntegerField("Met");
double PM = JsonObject->GetNumberField("PM");
//Add data to array
Arr1.Emplace(FString::FromInt(id));
Arr1.Emplace(nome);
Arr1.Emplace(DataInicial);
Arr1.Emplace(DataFinal);
Arr1.Emplace(FString::SanitizeFloat(VN));
Arr1.Emplace(FString::FromInt(CN));
Arr1.Emplace(FString::FromInt(Met));
Arr1.Emplace(FString::SanitizeFloat(PM));
UE_LOG(LogTemp, Warning, TEXT("===== GET LE ====="));
//FString teste = JsonObject->GetField("LE");
//UE_LOG(LogTemp, Warning, TEXT(teste));
//ArrSuco = JsonObject->GetArrayField("LE");
//TArray<TSharedPtr<FJsonValue>> objArray = JsonObject->GetArrayField("LE");
//ArrTeste = JsonObject->GetArrayField("LE");
//GEngine->AddOnScreenDebugMessage(1, 2.0f, FColor::Green, "printing LE...");
UE_LOG(LogTemp, Warning, TEXT("===== printing LE... ====="));
auto arr = JsonObject->GetArrayField("LE");
for (int32 index = 0; index < arr.Num(); index++)
{
//GEngine->AddOnScreenDebugMessage(1, 2.0f, FColor::Green, "name:" + FString(objArray[index]->AsString()));
UE_LOG(LogTemp, Warning, TEXT("TESTE"));
//ArrSuco
if (index == 0) {
//ArrSuco.Emplace(FString::FromInt();
UE_LOG(LogTemp, Warning, TEXT("Index = 0"));
//FString teste = arr[0].Value;
//auto arr2 = arr[0].Get()->TryGetArray;
//UE_LOG(LogTemp, Warning, TEXT(arr[0].Get()->AsString()));
//GEngine->AddOnScreenDebugMessage(1, 2.0f, FColor::Green, FString(sucoId));
//UE_LOG(LogTemp, Warning, TEXT(FString(arr[index]["Id"])));
//ArrSuco.Append(FString(arr[index]["Id"]), arr[index].Num());
//ArrSuco.Emplace(FString::FromInt(id));
//ArrSuco.Emplace(nome);
}
//ArrEspumante
else if (index == 1) {
UE_LOG(LogTemp, Warning, TEXT("Index = 1"));
}
//ArrCerveja
else if (index == 2) {
UE_LOG(LogTemp, Warning, TEXT("Index = 2"));
}
//ArrVinho
else if (index == 3) {
UE_LOG(LogTemp, Warning, TEXT("Index = 3"));
}
//UE_LOG(LogTemp, Warning, TEXT(objArray[index]->AsString()));
//UE_LOG(LogTemp, Warning, TEXT(FString(ArrSuco[index])));
}
//Count Array
//int32 CountArr = ArrSuco.Num();
}
}
I can print all (LE) indexes tests if (index == 0), but I can't put it to an array.
I really don't know how to get it, I'm stuck here all the day.

Did you try something like:
TArray<TSharedPtr<FJsonValue>> arr = JsonObject->GetArrayField("LE");
for (int32 index = 0; index < arr.Num(); index++)
{
TSharedPtr<FJsonObject> obj = arr[index]->AsObject();
/* get the object's fields:
obj->GetStringField("Nome");
*/
}

Related

Micropython User Module: Class Prints Initialized Data Even If Attributes Have Changed

Here's a visual representation of the problem from the front end. Notice that the output from printing the class does not change even if the attributes do, yet I get the proper value from printing the attributes directly.
import bitbanglab as bbl
class Entity(bbl.Entity):
def __init__(self):
super().__init__(bytearray([0x0F]), 1, 1, 2, 2, 8, 2)
print(self) #Entity(x:1, y:1, width:2, height:2, scale:8, len:1, pal:2)
self.x = 50
self.y = 20
self.width = 50
self.height= 60
self.scale = 10
self.len = 200
self.pal = 14
print(self) #Entity(x:1, y:1, width:2, height:2, scale:8, len:1, pal:2)
print(self.x) #50
print(self.y) #20
Entity()
Print Method
STATIC void Entity_print(const mp_print_t *print, mp_obj_t self_in, mp_print_kind_t kind) {
(void)kind;
bitbanglab_Entity_obj_t *self = MP_OBJ_TO_PTR(self_in);
mp_printf(print, "Entity(x:%u, y:%u, width:%u, height:%u, scale:%u, len:%u, pal:%u)", self->x, self->y, self->width, self->height, self->scale, self->len, self->pal);
}
get/set attributes
STATIC void Entity_attr(mp_obj_t self_in, qstr attr, mp_obj_t *dest) {
bitbanglab_Entity_obj_t *self = MP_OBJ_TO_PTR(self_in);
if (dest[0] == MP_OBJ_NULL) {
if (attr == MP_QSTR_x)
dest[0] = mp_obj_new_int(self->x);
else if(attr == MP_QSTR_y)
dest[0] = mp_obj_new_int(self->y);
else if(attr == MP_QSTR_width)
dest[0] = mp_obj_new_int(self->width);
else if(attr == MP_QSTR_height)
dest[0] = mp_obj_new_int(self->height);
else if(attr == MP_QSTR_scale)
dest[0] = mp_obj_new_int(self->scale);
else if(attr == MP_QSTR_len)
dest[0] = mp_obj_new_int(self->len);
else if(attr == MP_QSTR_pal)
dest[0] = mp_obj_new_int(self->pal);
} else {
if (attr == MP_QSTR_x)
self->x = mp_obj_get_int(dest[1]);
else if (attr == MP_QSTR_y)
self->y = mp_obj_get_int(dest[1]);
else if (attr == MP_QSTR_width)
self->width = mp_obj_get_int(dest[1]);
else if (attr == MP_QSTR_height)
self->height = mp_obj_get_int(dest[1]);
else if (attr == MP_QSTR_scale)
self->scale = mp_obj_get_int(dest[1]);
else if (attr == MP_QSTR_len)
self->len = mp_obj_get_int(dest[1]);
else if (attr == MP_QSTR_pal)
self->pal = mp_obj_get_int(dest[1]);
dest[0] = MP_OBJ_NULL;
}
}
Class Type
const mp_obj_type_t bitbanglab_Entity_type = {
{ &mp_type_type },
.name = MP_QSTR_bitbanglab,
.print = Entity_print,
.make_new = Entity_make_new,
.locals_dict = (mp_obj_dict_t*)&Entity_locals_dict,
.attr = Entity_attr,
};
Class Object
typedef struct _bitbanglab_Entity_obj_t {
mp_obj_base_t base;
uint8_t *bitmap;
uint16_t len;
uint16_t x;
uint16_t y;
uint16_t width;
uint16_t height;
uint8_t scale;
uint8_t pal;
} bitbanglab_Entity_obj_t;
Class
The class doesn't have any methods yet. The locals_dict_table for it is empty.
mp_obj_t Entity_make_new(const mp_obj_type_t *type, size_t n_args, size_t n_kw, const mp_obj_t *args) {
mp_arg_check_num(n_args, n_kw, 7, 7, true);
//make self
bitbanglab_Entity_obj_t *self = m_new_obj(bitbanglab_Entity_obj_t);
self->base.type = &bitbanglab_Entity_type;
//arguments
enum { ARG_bitmap, ARG_x, ARG_y, ARG_width, ARG_height, ARG_scale, ARG_pal};
//get buffer
mp_buffer_info_t bufinfo;
mp_get_buffer_raise(args[ARG_bitmap], &bufinfo, MP_BUFFER_RW);
//properties
self->bitmap = (uint8_t *)bufinfo.buf;
self->len = bufinfo.len;
self->x = mp_obj_get_int(args[ARG_x]);
self->y = mp_obj_get_int(args[ARG_y]);
self->width = mp_obj_get_int(args[ARG_width]);
self->height = mp_obj_get_int(args[ARG_height]);
self->scale = mp_obj_get_int(args[ARG_scale]);
self->pal = mp_obj_get_int(args[ARG_pal]);
return MP_OBJ_FROM_PTR(self);
}
I realized the problem. I was subclassing my user-module-defined class, and the values I was setting were not the ones on the super. If I instantiate the Entity class without a subclass and change the attributes, printing the class reflects those changes. Now my new problem is figuring out how to reach the super's attributes from a subclass. I'll update this answer to be stronger when I figure it all out.

unixODBC SQLExecute() error

Sometimes I get quite strange error message from SQLExecute() during INSERT. Have no idea how I can deal with this, other queries are ok.
Log
[ODBC][67383][1485443238.457802][SQLPrepare.c][196]
Entry:
Statement = 0x101022600
SQL = [INSERT INTO Core_Message(channel_id, date, member_id, reply_id) VALUES(25, '2017-01-26 18:07:18', 4, NULL)
][length = 109 (SQL_NTS)]
[ODBC][67383][1485443238.457893][SQLPrepare.c][377]
Exit:[SQL_SUCCESS]
[ODBC][67383][1485443238.458014][SQLExecute.c][187]
Entry:
Statement = 0x101022600
[ODBC][67383][1485443238.458189][SQLExecute.c][357]
Exit:[SQL_ERROR]
DIAG [HY000] no error information;
Error while preparing parameters
[ODBC][67383][1485443238.458543][SQLFreeHandle.c][381]
Entry:
Handle Type = 3
Input Handle = 0x101022600
[ODBC][67383][1485443238.458670][SQLFreeHandle.c][494]
Exit:[SQL_SUCCESS]
Code
SQLLEN length(0);
if (!isSuccess(SQLPrepare(_statement, (unsigned char *)query.c_str(), SQL_NTS))) {
_status = StatementStatus::Fault;
return false;
}
for (std::size_t i=0; i<reference_vector.size(); i++) {
length = reference_vector.at(i).get().length();
if (!isSuccess(SQLBindParameter(_statement, i + 1, SQL_PARAM_INPUT, SQL_C_BINARY, SQL_VARBINARY, reference_vector.at(i).get().length(), 0, (char *)reference_vector.at(i).get().c_str(), (SQLLEN)reference_vector.at(i).get().length(), &length))) {
_status = StatementStatus::Fault;
return false;
}
}
if (!isSuccess(SQLExecute(_statement))) {
_status = StatementStatus::Fault;
return false;
}
Tricky block with SQLBindParameter() event don't used in runtime.
Thanks in advance.

UnsafeMutablePointer in AURenderCallback

I can't understand, how I should use UnsafeMutablePointer in Swift 3. Especially in AURenderCallback.
I try below code:
import Foundation
import AudioToolbox
let sineFrequency = 880.0
// MARK: User data struct
struct SineWavePlayer {
var outputUnit: AudioUnit? = nil
var startingFrameCount: Double = 0
}
// MARK: Callback function
let SineWaveRenderProc: AURenderCallback = {(inRefCon, ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData) -> OSStatus in
var player = UnsafeMutablePointer<SineWavePlayer>(inRefCon)
var j = player.pointee.startingFrameCount
let cycleLength = 44100 / sineFrequency
for frame in 0..<inNumberFrames {
var buffers = UnsafeMutableAudioBufferListPointer(ioData)
UnsafeMutablePointer<Float32>(buffers[0].mData)[Int(frame)] = Float32(sin(2 * M_PI * (j / cycleLength)))
UnsafeMutablePointer<Float32>(buffers[1].mData)[Int(frame)] = Float32(sin(2 * M_PI * (j / cycleLength)))
// Or iterate through array:
// for buffer in buffers {
// UnsafeMutablePointer<Float32>(buffer.mData)[Int(frame)] = Float32(sin(2 * M_PI * (j / cycleLength)))
// }
j++
if j > cycleLength {
j -= cycleLength
}
}
player.pointee.startingFrameCount = j
return noErr
}
// MARK: Utility function
func CheckError(_ error: OSStatus, operation: String) {
guard error != noErr else {
return
}
var result: String = ""
var char = Int(error.bigEndian)
for _ in 0..<4 {
guard isprint(Int32(char&255)) == 1 else {
result = "\(error)"
break
}
result.append(String(describing: UnicodeScalar(char&255)))
char = char/256
}
print("Error: \(operation) (\(result))")
exit(1)
}
func CreateAndConnectOutputUnit(_ player: inout SineWavePlayer) {
// Generate a description that matches the output device (speakers)
var outputcd = AudioComponentDescription(componentType: kAudioUnitType_Output, componentSubType: kAudioUnitSubType_DefaultOutput, componentManufacturer: kAudioUnitManufacturer_Apple, componentFlags: 0, componentFlagsMask: 0)
let comp = AudioComponentFindNext(nil, &outputcd)
if comp == nil {
print("Can't get output unit")
exit(-1)
}
CheckError(AudioComponentInstanceNew(comp!, &player.outputUnit),
operation: "Couldn't open component for outputUnit")
// Register the render callback
var input = AURenderCallbackStruct(inputProc: SineWaveRenderProc, inputProcRefCon: &player)
CheckError(AudioUnitSetProperty(player.outputUnit!, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 0, &input, UInt32(MemoryLayout<AURenderCallbackStruct>.size)),
operation: "AudioUnitSetProperty failed")
// Initialize the unit
CheckError(AudioUnitInitialize(player.outputUnit!),
operation: "Couldn't initialize output unit")
}
func main() {
var player = SineWavePlayer()
// Set up output unit and callback
CreateAndConnectOutputUnit(&player)
// Start playing
CheckError(AudioOutputUnitStart(player.outputUnit!),
operation: "Couldn't start output unit")
// Play for 5 seconds
sleep(5)
// Clean up
AudioOutputUnitStop(player.outputUnit!)
AudioUnitUninitialize(player.outputUnit!)
AudioComponentInstanceDispose(player.outputUnit!)
}
main()
But this line of code
var player = UnsafeMutablePointer<SineWavePlayer>(inRefCon)
is not working. How to translate this line to Swift 3?
Please, help me.
In Swift 3, initializers cannot be used to convert pointer types. In your case, the type of inRefCon is UnsafeMutableRawPointer, so you need to use assumingMemoryBound(to:) method.
And one more, the address of player passed to the callback needs to be stable all while the sound is playing, addresses taken from inout arguments (specified by & prefix) does not fulfil this requirement.
The two things above fixed, your code would be something like this:
import Foundation
import AudioToolbox
let sineFrequency = 880.0
// MARK: User data struct
struct SineWavePlayer {
var outputUnit: AudioUnit? = nil
var startingFrameCount: Double = 0
}
// MARK: Callback function
let SineWaveRenderProc: AURenderCallback = {(inRefCon, ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData) -> OSStatus in
var player = inRefCon.assumingMemoryBound(to: SineWavePlayer.self)
var j = player.pointee.startingFrameCount
let cycleLength = 44100 / sineFrequency
for frame in 0..<inNumberFrames {
var buffers = UnsafeMutableAudioBufferListPointer(ioData)
buffers?[0].mData?.assumingMemoryBound(to: Float32.self)[Int(frame)] = Float32(sin(2 * M_PI * (j / cycleLength)))
buffers?[1].mData?.assumingMemoryBound(to: Float32.self)[Int(frame)] = Float32(sin(2 * M_PI * (j / cycleLength)))
j += 1
if j > cycleLength {
j -= cycleLength
}
}
player.pointee.startingFrameCount = j
return noErr
}
// MARK: Utility function
func CheckError(_ error: OSStatus, operation: String) {
guard error != noErr else {
return
}
var result: String = ""
var char = Int(error.bigEndian)
for _ in 0..<4 {
guard isprint(Int32(char&255)) == 1 else {
result = "\(error)"
break
}
result.append(String(describing: UnicodeScalar(char&255)))
char = char/256
}
print("Error: \(operation) (\(result))")
exit(1)
}
func CreateAndConnectOutputUnit(_ playerPtr: UnsafeMutablePointer<SineWavePlayer>) {
// Generate a description that matches the output device (speakers)
var outputcd = AudioComponentDescription(componentType: kAudioUnitType_Output, componentSubType: kAudioUnitSubType_DefaultOutput, componentManufacturer: kAudioUnitManufacturer_Apple, componentFlags: 0, componentFlagsMask: 0)
let comp = AudioComponentFindNext(nil, &outputcd)
if comp == nil {
print("Can't get output unit")
exit(-1)
}
CheckError(AudioComponentInstanceNew(comp!, &playerPtr.pointee.outputUnit),
operation: "Couldn't open component for outputUnit")
// Register the render callback
var input = AURenderCallbackStruct(inputProc: SineWaveRenderProc, inputProcRefCon: playerPtr)
CheckError(AudioUnitSetProperty(playerPtr.pointee.outputUnit!, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input, 0, &input, UInt32(MemoryLayout<AURenderCallbackStruct>.size)),
operation: "AudioUnitSetProperty failed")
// Initialize the unit
CheckError(AudioUnitInitialize(playerPtr.pointee.outputUnit!),
operation: "Couldn't initialize output unit")
}
func main() {
let playerPtr = UnsafeMutablePointer<SineWavePlayer>.allocate(capacity: 1)
defer {playerPtr.deallocate(capacity: 1)}
playerPtr.initialize(to: SineWavePlayer())
defer {playerPtr.deinitialize()}
// Set up output unit and callback
CreateAndConnectOutputUnit(playerPtr)
// Start playing
CheckError(AudioOutputUnitStart(playerPtr.pointee.outputUnit!),
operation: "Couldn't start output unit")
// Play for 5 seconds
sleep(5)
// Clean up
AudioOutputUnitStop(playerPtr.pointee.outputUnit!)
AudioUnitUninitialize(playerPtr.pointee.outputUnit!)
AudioComponentInstanceDispose(playerPtr.pointee.outputUnit!)
}

Object reference not set to an instance Of Object

Good day to all,
Please I need somebody to help me have a look at my codes.I am having this error of** Object reference not set to an instance Of Object**.It appears the error is within this lines of codes
if (_scrollingTimer == null)
{
_scrollingTimer = new Timer()
{
Enabled = false,
Interval = 500,
Tag = (sender as TrackBar).Value
};
but unfortunately I was unable to resolve this error.I would be very glad if somebody could help me out.thank you for the usual support.best regards.
Firstoption.
Below are the remaining part of the codes.
byte[] data = new byte[5];
private Timer _scrollingTimer = null;
private void button3_Click(object sender, EventArgs e)
{
UInt32 numBytesWritten = 0;
data[0] = 1;
myFtdiDevice.Write(data, 1, ref numBytesWritten);
data[0] = 0x6A;
myFtdiDevice.Write(data, 1, ref numBytesWritten);
}
private void trackBar1_Scroll(object sender, EventArgs e)
{
if(!backgroundWorker1.IsBusy)
{
backgroundWorker1.RunWorkerAsync();
}
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
UInt32 numBytesWritten = 1;
string dataToWrite = "#0";
if (_scrollingTimer == null)
{
_scrollingTimer = new Timer()
{
Enabled = false,
Interval = 500,
Tag = (sender as TrackBar).Value
};
_scrollingTimer.Tick += (s, ea) =>
{
if (trackBar1.Value == (int)_scrollingTimer.Tag)
{
_scrollingTimer.Stop();
myFtdiDevice.Write(dataToWrite, dataToWrite.Length, ref numBytesWritten);
int percent = (int)(((double)trackBar1.Value / (double)trackBar1.Maximum) * 100);
label2.Text = (percent.ToString()) + "%";
data[0] = Convert.ToByte(percent);
data[1] = 0x6A;
myFtdiDevice.Write(data, 2, ref numBytesWritten);
_scrollingTimer.Dispose();
_scrollingTimer = null;
}
else
{
_scrollingTimer.Tag = trackBar1.Value;
}
};
_scrollingTimer.Start();
}
}
sender is not a TrackBar. Looks like it's probably backgroundWorker1.

Open XML Excel Cell Formatting

I am trying to export to excel using Open XML with simple formatting. Export to Excel is working. The problem is with formatting the data. I am trying to have very basic formatting. i.e. the Column names should be in bold and rest of the content in normal font. This is what I did. Please let me know where am I going wrong.
private Stylesheet GenerateStyleSheet()
{
return new Stylesheet(
new Fonts(
new Font(new DocumentFormat.OpenXml.Spreadsheet.FontSize { Val = 12},
new Bold(),
new Font(new DocumentFormat.OpenXml.Spreadsheet.FontSize { Val = 12}))
)
);
}
protected void ExportExcel(DataTable dtExport)
{
Response.ClearHeaders();
Response.ClearContent();
Response.Clear();
Response.Buffer = true;
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml";
//"application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml" '"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" '"application/vnd.ms-excel"
Response.AddHeader("content-disposition", "attachment; filename=Test.xlsx");
Response.Charset = "";
this.EnableViewState = false;
MemoryStream ms = new MemoryStream();
SpreadsheetDocument objSpreadsheet = SpreadsheetDocument.Create(ms, SpreadsheetDocumentType.Workbook);
WorkbookPart objWorkbookPart = objSpreadsheet.AddWorkbookPart();
objWorkbookPart.Workbook = new Workbook();
WorksheetPart objSheetPart = objWorkbookPart.AddNewPart<WorksheetPart>();
objSheetPart.Worksheet = new Worksheet(new SheetData());
Sheets objSheets = objSpreadsheet.WorkbookPart.Workbook.AppendChild<Sheets>(new Sheets());
Sheet objSheet = new Sheet();
objSheet.Id = objSpreadsheet.WorkbookPart.GetIdOfPart(objSheetPart);
objSheet.SheetId = 1;
objSheet.Name = "mySheet";
objSheets.Append(objSheet);
WorkbookStylesPart stylesPart = objSpreadsheet.WorkbookPart.AddNewPart<WorkbookStylesPart>();
stylesPart.Stylesheet = GenerateStyleSheet();
stylesPart.Stylesheet.Save();
objSheetPart.Worksheet.Save();
objSpreadsheet.WorkbookPart.Workbook.Save();
for (int cols = 0; cols < dtExport.Columns.Count; cols++)
{
Cell objCell = InsertCellInWorksheet(GetColumnName(cols), 1, objSheetPart);
objCell.CellValue = new CellValue(dtExport.Columns[cols].ColumnName);
objCell.DataType = new EnumValue<CellValues>(CellValues.String);
objCell.StyleIndex = 0;
}
objSheetPart.Worksheet.Save();
objSpreadsheet.WorkbookPart.Workbook.Save();
for (uint row = 0; row < dtExport.Rows.Count; row++)
{
for (int cols = 0; cols < dtExport.Columns.Count; cols++)
{
//row + 2 as we need to start adding data from second row. First row is left for header
Cell objCell = InsertCellInWorksheet(GetColumnName(cols), row + 2, objSheetPart);
objCell.CellValue = new CellValue(Convert.ToString(dtExport.Rows[Convert.ToInt32(row)][cols]));
objCell.DataType = new EnumValue<CellValues>(CellValues.String);
objCell.StyleIndex = 1;
}
}
objSheetPart.Worksheet.Save();
objSpreadsheet.WorkbookPart.Workbook.Save();
objSpreadsheet.Close();
ms.WriteTo(Response.OutputStream);
Response.Flush();
Response.End();
}
// Given a column name, a row index, and a WorksheetPart, inserts a cell into the worksheet.
// If the cell already exists, return it.
private Cell InsertCellInWorksheet(string columnName, uint rowIndex, WorksheetPart worksheetPart)
{
Worksheet worksheet = worksheetPart.Worksheet;
SheetData sheetData = worksheet.GetFirstChild<SheetData>();
string cellReference = (columnName + rowIndex.ToString());
// If the worksheet does not contain a row with the specified row index, insert one.
Row row = default(Row);
if ((sheetData.Elements<Row>().Where(r => r.RowIndex.Value == rowIndex).Count() != 0))
{
row = sheetData.Elements<Row>().Where(r => r.RowIndex.Value == rowIndex).First();
}
else
{
row = new Row();
row.RowIndex = rowIndex;
sheetData.Append(row);
}
// If there is not a cell with the specified column name, insert one.
if ((row.Elements<Cell>().Where(c => c.CellReference.Value == columnName + rowIndex.ToString()).Count() > 0))
{
return row.Elements<Cell>().Where(c => c.CellReference.Value == cellReference).First();
}
else
{
// Cells must be in sequential order according to CellReference. Determine where to insert the new cell.
Cell refCell = null;
foreach (Cell cell in row.Elements<Cell>())
{
if ((string.Compare(cell.CellReference.Value, cellReference, true) > 0))
{
refCell = cell;
break; // TODO: might not be correct. Was : Exit For
}
}
Cell newCell = new Cell();
newCell.CellReference = cellReference;
row.InsertBefore(newCell, refCell);
return newCell;
}
}
It seems like you are missing a ")" after your first font creation. So then you end opp with only one font index (the default one)
Below is the code I use for exactly what you are asking for.
You might remove fills and borders and remove them from cellformat, but I had some syntax problems while writing this so I just left it when it all worked :-)
private Stylesheet GenerateStyleSheet()
{
return new Stylesheet(
new Fonts(
// Index 0 - Default font.
new Font(
new FontSize() { Val = 11 },
new Color() { Rgb = new HexBinaryValue() { Value = "000000" } }
),
new Font(
new Bold(),
new FontSize() { Val = 11 },
new Color() { Rgb = new HexBinaryValue() { Value = "000000" } }
)
),
new Fills(
// Index 0 - Default fill.
new Fill(
new PatternFill() { PatternType = PatternValues.None })
),
new Borders(
// Index 0 - Default border.
new Border(
new LeftBorder(),
new RightBorder(),
new TopBorder(),
new BottomBorder(),
new DiagonalBorder())
),
new CellFormats(
// Index 0 - Default cell style
new CellFormat() { FontId = 0, FillId = 0, BorderId = 0 },
new CellFormat() { FontId = 1, FillId = 0, BorderId = 0, ApplyFont = true }
)
);
}