unable to download xlsx file using POI - spring-mvc

Hi i working on poi poc to generate xlsx file in webapplication i was able to render excel standalone well but when i integrate codebase in my project i was getting below error.
below is code base base to download xlsx file in webapplication
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet spreadsheet = workbook.createSheet("Sheet1");
XSSFRow row = spreadsheet.createRow(0);
XSSFCell cell;
while (response.nextResultSet()) {
resultSet = response.getResultSet();
Object[] columnMetaData = resultSet.getColumnNames();
int columnCount = columnMetaData.length;
//Columns Loop
ArrayList<String> columns = new ArrayList<String>();
for (int i = 1; i < columnCount; i++) {
String columnName = (String) columnMetaData[i];
columns.add(columnName);
cell = row.createCell(i-1);
cell.setCellValue(columnName);
}
int i=1;
while (resultSet.nextRow()) {
row = spreadsheet.createRow(i);
i++; // counter for each row of data
for (int j = 0; j < columnMetaData.length; j++)
{
String keyVal = String.valueOf(columnMetaData[j]);
String value = (String)resultSet.getValue(keyVal);
cell = row.createCell(j);
cell.setCellValue(value);
}
}
log.info("value if i--->" + i);
for (int k = 1; k < columnCount; k++) {
spreadsheet.autoSizeColumn(k-1);
}
}
ByteArrayOutputStream outByteStream = new ByteArrayOutputStream();
workbook.write(outByteStream);
context.getResponse().setHeader("content-disposition", "inline;filename=" + calendar.getTimeInMillis() + ".xlsx");
context.getResponse().setContentType("application/Excel");
context.getRequest().setAttribute("called_from", "excel");
//context.getResponse().setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
//context.getResponse().setHeader("Content-Disposition", "attachment; filename=testxls.xlsx");
}
OutputStream os = null;
os = context.getResponse().getOutputStream();
byte [] outArray = is.toByteArray();
context.getResponse().setContentLength(outArray.length);
os.write(outArray);
log.info(os.toString());
os.flush();

Related

Create 2 or more text files with ASP.NET

I have created a web app which creates 1 text file. Inside this text file it is created 1000 rows with the same word "TRY AGAIN". After this each 50 rows I put a random code which means in 1000 rows, 20 rows are random.
This is my code:
static Random randNum = new Random();
public static string Random(int ran)
{
string _charachters = "ABCDEFGHIJKMLNOPQRSTUVWXYZ0123456789";
char[] chars = new char[ran];
int allowedCharCount = _charachters.Length;
for (int i = 0; i < ran; i++)
{
chars[i] = _charachters[(int)((_charachters.Length) * randNum.NextDouble())];
}
return new string(chars);
}
protected void Button1_Click(object sender, EventArgs e)
{
string pathCreate = #"C:\" + TextBox3.Text + ".txt";
if (!File.Exists(pathCreate))
{
using (StreamWriter sw = File.CreateText(pathCreate))
{
for (int i = 1; i <= int.Parse(TextBox1.Text); i++)
{
sw.WriteLine("TRY AGAIN.");
}
}
}
string pathRandom = #"C:\" + TextBox3.Text + ".txt";
string[] lines = File.ReadAllLines(pathRandom);
for (int i = 0; i < lines.Length; i += int.Parse(TextBox2.Text))
{
lines[i] = lines[i].Replace("TRY AGAIN.", Random(int.Parse("7")));
}
File.WriteAllLines(pathRandom, lines);
}
Now I want to create 2 ore more text files with one click of a button. And on each text file there will be random codes (not duplicates). Any idea?
Thank You.
I found the solution. It is late in my country and my brain barely works. :P
for(int j = 1; j <= 10; j++)
{
string pathKrijo = #"C:\inetpub\wwwroot\KODET\" + j.ToString() + ".txt";
using (StreamWriter sw = File.CreateText(pathKrijo))
{
for (int i = 1; i <= 100; i++)
{
sw.WriteLine("Provo Përsëri.");
}
}
string pathKodFitues = #"C:\inetpub\wwwroot\KODET\" + j.ToString() + ".txt";
string[] lines = File.ReadAllLines(pathKodFitues);
for (int i = 0; i < lines.Length; i += 10)
{
lines[i] = lines[i].Replace("Provo Përsëri.", Random(int.Parse("7")));
}
File.WriteAllLines(pathKodFitues, lines);
}

Read text file saved in SD card line by line

I have data.txt file saved in SD card containing values of variables required for driving 3 stepper motors. I want to read data.txt file line by line, split the line by "," and save each values into respective variables. data.txt file has data something like this:
8.24, 5.67, 7.34
3,86, 3.56, 4.49
5.38, 6.29, 3.67
I want to save value of first integer in x, second in y and third in z and execute the code. Once the code is executed, I want to get next line and load respective values in their respective variables and continue the loop till there is no line left in data.txt file
This code for matrix, let change some type that you need
public Matrix loadIntMapData(InputStream input) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
String line;
ArrayList<double[]> list = new ArrayList<double[]>();
while ((line = reader.readLine()) != null) {
if (line.equals("")) {
//ignore
} else {
String[] vs = line.split(",");
double ints[] = new double[vs.length];
for (int i = 0; i < ints.length; i++) {
ints[i] = Double.parseDouble(vs[i]);
}
list.add(ints);
}
}
double[][] map = new double[list.size()][];
for (int i = 0; i < map.length; i++) {
map[i] = list.get(i);
}
return new Matrix(map);
}
public static final void writInteMapData(Matrix matrix, File file) throws IOException {
double[][] map = matrix.getArray();
StringBuffer output = new StringBuffer();
for (int i = 0; i < map.length; i++) {
for (int j = 0; j < map[i].length; j++) {
output.append(Double.toString(map[i][j]));
if (j != map[i].length - 1) {
output.append(",");
}
}
if (i != map.length - 1) {
output.append("\r\n");
}
}
BufferedWriter writer = new BufferedWriter(new FileWriter(file));
writer.write(output.toString());
writer.close();
}

getting out of memory exception while using fileStream

I am facing an Issue while uploading file from a web page to server. It works fine for files upto 200 MB, but starts throwing out of memory exception.
Could you please help me
I have pasted the code below
private void UploadToServer(HttpPostedFile oHttpPostedFile)
{
string CalCheckSum = string.Empty;
try
{
string FileName = getFileName(oHttpPostedFile.FileName.Trim());
if (File.Exists(Server.MapPath("Upload") + "\\" + System.IO.Path.GetFileName(FileName)))
{
File.Delete(Server.MapPath("Upload") + "\\" + System.IO.Path.GetFileName(FileName));
}
string serverFilePath = Server.MapPath("Upload") + "\\" + System.IO.Path.GetFileName(FileName);
FileStream fs = new FileStream(serverFilePath, FileMode.CreateNew);
string strFileFormName = serverFilePath;
// Uri oUri = new Uri(strUrl);
// DFB: Upload goes into stream
Stream myStream = oHttpPostedFile.InputStream;
string _name = oHttpPostedFile.FileName;
string _contentType = oHttpPostedFile.ContentType;
// DFB: Create buffer for stream
Byte[] myBuffer;
myBuffer = new byte[10240];
if (myStream.Length == 0)
{
//Zero Bytes file Can not be processed
CalCheckSum = string.Empty;
return;
}
else if (myStream.Length > 10240)
myBuffer = new byte[10240];
else
myBuffer = new byte[myStream.Length];
StringBuilder filecontent = new StringBuilder();
int fileLength = (int)myStream.Length;
int length = (int)myStream.Length / myBuffer.Length + 1;
int lastPacketLength = (int)myStream.Length % 10240;
int count = 1;
while (myStream.Read(myBuffer, 0, myBuffer.Length) > 0)
{
if (count == length)
fs.Write(myBuffer, 0, lastPacketLength);
else
fs.Write(myBuffer, 0, myBuffer.Length);
count++;
}
fs.Close();
fs.Dispose();
myStream.Dispose();
myBuffer = null;
myStream = null;
FileStream fileStream = File.OpenRead(serverFilePath);
byte[] pbytCombinedArrays = new byte[fileLength];
int numBytesToRead = fileLength;
int numBytesRead = 0;
while (numBytesToRead > 0)
{
// Read may return anything from 0 to numBytesToRead.
int n = fileStream.Read(pbytCombinedArrays, numBytesRead, numBytesToRead);
// Break when the end of the file is reached.
if (n == 0)
break;
numBytesRead += n;
numBytesToRead -= n;
}
fileStream.Dispose();
fileStream.Close();
}
You get the exception because you are trying to allocate more memory than is allowed for the application. Web applications are generally limited to about 300 MB.
The solution would be to avoid reading the entire file into memory. It's simply too large for a web application to handle all at once.

saving data from datagrid c#

hi guys i am new to c# and i was making a text editor program using data grid view. The problem is when i open a text file to my data grid, then when i press save i get the error saying "Index was outside the bounds of the array". I included my code below. Any suggestions can be a big help for me. I included my code below.
// edit file button
dataGridView1.Columns.Add("colname", "Question");
dataGridView1.Columns.Add("colname", "Answer 1");
dataGridView1.Columns.Add("colname", "Answer 2");
dataGridView1.Columns.Add("colname", "Answer 3");
dataGridView1.Columns.Add("colname", "Answer 4");
dataGridView1.Columns.Add("colname", "Correct Answer");
dataGridView1.Columns[5].ReadOnly = true;
dataGridView1.Columns[5].DefaultCellStyle.BackColor = Color.DimGray;
dataGridView1.AllowUserToAddRows = true;
StreamReader sr = new StreamReader(fName);
string Contents = sr.ReadToEnd();
string[] strArray = { Contents };
for (int r = 0; r <= dataGridView1.Rows.Count - 1; r++)
{
for (int c = 0; c <= dataGridView1.Columns.Count - 1; c++)
{
dataGridView1.Rows.Add(strArray[r].Split('|')); //getting the error here
}
}
//save button
private void button2_Click(object sender, EventArgs e)
{
//dataGridView1.AllowUserToAddRows = false;
if (dataGridView1.Visible)
{
string fName = "C:\\Documents and Settings\\" + txtFileName.Text + ".txt";
System.IO.StreamWriter file = new System.IO.StreamWriter(fName);
string sLine = "";
for (int r = 0; r <= dataGridView1.Rows.Count - 1; r++)
{
for (int c = 0; c <= dataGridView1.Columns.Count - 1; c++)
{
sLine = sLine + dataGridView1.Rows[r].Cells[c].Value;
if (c != dataGridView1.Columns.Count - 1)
{
sLine = sLine + "|";
}
}
file.WriteLine(sLine);
sLine = "";
}
file.Close();
System.Windows.Forms.MessageBox.Show("Save Complete.", "Program Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
dataGridView1.DataSource = "";
dataGridView1.Visible = false;
}
else
{
string cap = "Confirmation";
string message = "Nothing to save";
MessageBoxButtons Btn2 = MessageBoxButtons.OK;
MessageBox.Show(message, cap, Btn2);
}
}
Thanks again for the help
Initially there is a dataGridView1.Rows.Count
Inside the loop u r doing this
dataGridView1.Rows.Add, which increments dataGridView1.Rows.Count by 1 every single time
so it comes back into the loop after the processing
try declaring int gridRowcount = dataGridView1.Rows.Count;
and then replace (int r = 0; r <= dataGridView1.Rows.Count - 1; r++)
for (int r = 0; r <= gridRowcount - 1; r++) and try
just guessing

Using OpenXML to insert a datatable into excel

I have a datatable that - depending on the user selection - will generate a dynamic datatable with any number of rows and columns. I'm currently using OpenXml to manipulate said spreadsheet. How would I go about inserting a datatable?
Thanks
Stu
I found some code which I was able to modify to suit my needs. Hope someone finds this useful.
public void ExportDataTable(System.Data.DataTable exportData, SheetData sheetData)
{
//add column names to the first row
Row header = new Row();
header.RowIndex = (UInt32)42;
SheetData sheetData2 = new SheetData();
foreach (DataColumn column in exportData.Columns)
{
Cell headerCell = createTextCell(exportData.Columns.IndexOf(column) + 1, Convert.ToInt32(header.RowIndex.Value), column.ColumnName);
header.AppendChild(headerCell);
}
sheetData.AppendChild(header);
//loop through each data row
DataRow contentRow;
int startRow = 43;
for (int i = 0; i < exportData.Rows.Count; i++)
{
contentRow = exportData.Rows[i];
sheetData.AppendChild(createContentRow(contentRow, i + startRow));
}
}
private Cell createTextCell(int columnIndex, int rowIndex, object cellValue)
{
Cell cell = new Cell();
cell.DataType = CellValues.InlineString;
cell.CellReference = getColumnName(columnIndex) + rowIndex;
InlineString inlineString = new InlineString();
Text t = new Text();
t.Text = cellValue.ToString();
inlineString.AppendChild(t);
cell.AppendChild(inlineString);
return cell;
}
private Row createContentRow(DataRow dataRow, int rowIndex)
{
Row row = new Row
{
RowIndex = (UInt32)rowIndex
};
for (int i = 0; i < dataRow.Table.Columns.Count; i++)
{
Cell dataCell = createTextCell(i + 1, rowIndex, dataRow[i]);
row.AppendChild(dataCell);
}
return row;
}
private string getColumnName(int columnIndex)
{
int dividend = columnIndex;
string columnName = String.Empty;
int modifier;
while (dividend > 0)
{
modifier = (dividend - 1) % 26;
columnName = Convert.ToChar(65 + modifier).ToString() + columnName;
dividend = (int)((dividend - modifier) / 26);
}
return columnName;
}

Resources